Check if String is Base64 in PHP

This tutorial will discuss how to check if string is base64 in PHP.

To check if a string is Base64 encoded in PHP, we can follow these steps:

  • Call the base64_decode() function and pass the string as an argument. This function will decode the string from Base64 format.
  • Take the decoded string and encode it back into Base64 using the base64_encode() function.
  • Compare the re-encoded string with the original string that was passed to the function. If they match, it means the original string was indeed Base64 encoded.

We have created a separate function,

function isBase64Encoded($strValue)
{
    return base64_encode(base64_decode($strValue, true)) === $strValue;
}

It accepts a string as an argument and returns true if the given string is Base64 encoded.

Please note that the function should handle any errors or exceptions that may occur during the decoding and encoding process.

Let’s see the complete example,

<?php
/**
 * Check if a string is Base64 encoded.
 *
 * @param string $strValue The string to validate.
 * @return bool True if the string is Base64 encoded, false otherwise.
 */
function isBase64Encoded($strValue)
{
    return base64_encode(base64_decode($strValue, true)) === $strValue;
}

// Base64 encoded string
$strValue = 'SGVsbG8gd29ybGQ=';

// Check if string contains a valid Base64 String
if (isBase64Encoded($strValue)) {
    echo "The string is Base64 encoded.";
} else {
    echo "The string is not Base64 encoded.";
}
?>

Output

The string is Base64 encoded.

Summary

Today, we learned how to check if string is base64 in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top