5

There is an image in string format, outputting that string with some mime type headers would be enough to render it on a page, how to check if that string is an image?

1
  • By "string format" do you mean base64? If so you should look into magic number libraries. (The most common of these is simply called "magic.") Commented May 19, 2012 at 8:48

1 Answer 1

11

"An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded."

Example:

<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
       . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
       . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
       . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);

$im = imagecreatefromstring($data);
if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
}
else {
    echo 'An error occurred.';
}
?>

http://php.net/manual/en/function.imagecreatefromstring.php

Sign up to request clarification or add additional context in comments.

3 Comments

You need to suppress errors using '@' or else you are doomed for that imagecreatefromstring() .
@ngen Any way to avoid getting doomed and at the same time avoid using @?
@YuriKolovsky You can't . Since you are trying to load a string into a function which is expecting an image. It will fail 1) if the image data is corrupt . 2) if it's not an image.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.