Detecting base64 encoded strings

Bill

84.***.***.***
1,040 days ago

Detecting base64 encoded strings

I came across this simple but useful script today in the PHP documentation commentaries, from Morgan Galpin. It allows you to true/false whether a string is of valid base64 format.. as you wouldn't want to base64_decode() something that isn't. :)

Code:

<?php
/**
* Check a string of base64 encoded data to make sure it has actually
* been encoded.
*
* @param $encodedString string Base64 encoded string to validate.
* @return Boolean Returns true when the given string only contains
* base64 characters; returns false if there is even one non-base64 character.
*/
function checkBase64Encoded($encodedString) {
$length = strlen($encodedString);

// Check every character.
for ($i = 0; $i < $length; ++$i) {
$c = $encodedString[$i];
if (
($c < '0' || $c > '9')
&& ($c < 'a' || $c > 'z')
&& ($c < 'A' || $c > 'Z')
&& ($c != '+')
&& ($c != '/')
&& ($c != '=')
) {
// Bad character found.
return false;
}
}
// Only good characters found.
return true;
}
?>



Base64 is useful for a lot of things so I thought I'd bring this up from the dungeons of the PHP manual and into a thread of its own.

http://en.wikipedia.org/wiki/Base64
http://php.net/manual/en/function.base64-encode.php
http://php.net/manual/en/function.base64-decode.php