4

How to test if a base64 string is a valid image in PHP?

I tried the following code:

function convertAndSaveLogo($data, $id){
        if(isset($data->base64_image) && $data->base64_image){
            $imageData = base64_decode($data->base64_image);
            if($imageData){
                $source = imagecreatefromstring($imageData);
                if($source){
                    imagepng($source, getcwd()."../dir/image/".$id.".png", 5);
                    imagedestroy($source);
                }
            }
        }
    }

But it is not working.

2 Answers2

2

Try this:

if(base64_encode(base64_decode($img, true)) === $img)
   echo 'is a Base64-encoded string' ;
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
1

Look into two things

  1. if $data->base64_image doesn't contain something like: 'data:image/jpeg;base64,', in my case replacing it to nothing does the job:

    //in my case base64 data resides in: \Input::all()['img_data']
    $base64img = str_replace(
         'data:image/jpeg;base64,', 
         '', 
         \Input::all()['img_data']
    );
    
    $data = base64_decode($base64img);
    
  2. if you're saving that you can as well check this solution :

    // if it returns FALSE then the uploaded file
    // isn't a valid image
    getimagesize($created_file); 
    
Tom St
  • 908
  • 8
  • 15
  • I don't want to save the file if the base64 is not a valid encoded image. So I can not use getimagesize. –  Apr 12 '15 at 21:18