Detect Base64 Encoding in PHP

Is there a bulletproof way to detect base64 encoding in a string in php?

I will post Yoshi's comment as the final conclusion:

I think you're out of luck. The false positives you mention, still are valid base64 encodings. You'd need to judge whether the decoded version makes any sense, but that will probably be a never ending story, and ultimately would probably also result in false positives. – Yoshi

How to detect true base64 on PHP

Since base64 is a mapping from 8 bit to 6 bit representation of data. You have just the following options:

  • Look for non-ASCII chars (other than A-Z, a-z, 0-9, +, /) and paddings
  • Look for the number of characters (it must be dividable by three).

By this way, you can check whether the data is not base64 encoded. But you cannot check whether the data is real base64, since it can be a normal string passing the requirements of base64 encoding.

On the other hand, if you know the structure of the data, it is possible to check that the decoding of base64 text fits the structure.

Is string base 64 encoded?

Attempt to decode it strictly against the Base64 alphabet. The second parameter allows you to enforce this strict check; by leaving it out, the decoding function simply strips out illegal characters before decoding:

if (base64_decode($str, true) === false)
{
echo 'Not a Base64-encoded string';
}

Detecting image type from base64 string in PHP

FileInfo can do that for you:

$encoded_string = "....";
$imgdata = base64_decode($encoded_string);

$f = finfo_open();

$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);

Passing base64 encoded strings in URL

No, you would need to url-encode it, since base64 strings can contain the "+", "=" and "/" characters which could alter the meaning of your data - look like a sub-folder.

Valid base64 characters are below.

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=

Get image type from base64 encoded src string

Well you have basically two options:

  1. Trust the metadata
  2. Type check the image source directly

Option 1:

Probably the quicker way because it only involve splitting string, but it may be incorrect.
Something like:

$data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA.';
$pos = strpos($data, ';');
$type = explode(':', substr($data, 0, $pos))[1];

Option 2:

Use getimagesize() and it's equivalent for string:

$info = getimagesizefromstring(explode(',', base64_decode($data)[1], 2));
// $info['mime']; contains the mimetype


Related Topics



Leave a reply



Submit