Tuesday, May 28, 2013

Parsing a Base64 encoded image string in PHP

Here's a quick way to parse a Base64 encoded image file to check if it's a proper image file. First, the PHP code:

$file_encoded = '[very LONG BASE64 STRING]';

$file_decoded = base64_decode($file_encoded);

$info = getimagesizefromstring($file_decoded);


If the decoded data is a valid image, the getimagesizefromstring() function will return the following info if said string is a proper image:

    [0] => 240
    [1] => 464
    [2] => 3
    [3] => width="240" height="464"
    [bits] => 8
    [mime] => image/png

Which makes it perfect for image validation. It returns FALSE if it's not able to parse the input as an image.

You'll need to have the GD image library installed to use this function.