0

In my cakephp program, I am converting a base64 encoded image to an image and then storing it in a folder.

How can I validate this image, before conversion?

The string is like data:image/png;base64,iVBORw0KG......
(The image can be of any extension not only png.)

Cory Charlton
  • 8,868
  • 4
  • 48
  • 68
user3398902
  • 13
  • 1
  • 7
  • http://codeaid.net/php/check-if-the-file-is-a-png-image-file-by-reading-its-signature – 72DFBF5B A0DF5BE9 Mar 25 '14 at 16:36
  • You want to validate the image before you convert to base64? What are you validating against, in that case? – bronzehedwick Mar 25 '14 at 16:39
  • Its an API in PHP for an IOS app.Im getting base 64 encrypted image , i just want to validate it and convert it to image and store it in a folder.Conversion working fine.How can i validate this encoded image – user3398902 Mar 25 '14 at 16:43

1 Answers1

1

This answer might be useful for processing the image.
This answer might be useful for validating the image.

Code:

$data = 'data:image/png;base64,iVBORw0KG.....';

list($type, $data) = explode(';base64,', $data, 2);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);

if (imagecreatefromstring($data) == false) { echo "invalid_image"; die(); }

file_put_contents('/storage/folder/image.png', $data);

You might also want to restrict file types.

You must keep in mind that you can't simply trust any of the data sent from the client (like 'data:image/png'), so you must rely on other means (some php functions).

dragonfire
  • 407
  • 7
  • 16