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);

print_r($size);

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

Array
(
    [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.

Monday, May 27, 2013

SELECT COUNT(*) using Drupal db_select

Here's how to use Drupal's db_select function to perform a SQL equivalent of:

SELECT COUNT(uid) FROM users WHERE name = $username