Saving a base64 code into a folder gives me a failed image and cannot open it with PHP

39 Views Asked by At

I am trying to save an image into a folder of my project, and file is saved but wrong, making it impossible to see or open.

First of all, I get the image through a form where base64 image code is captured, after picking it. And then, when I submit the post, I go with this code:

var selectFotoAdjunta = document.getElementById("fotoAdjunta__url_val"); var selectedFotoAdjunta = selectFotoAdjunta.src; var selectedEncodedFotoAdjunta = encodeURIComponent(selectedFotoAdjunta);

And then, I send variable through the post system:

var $form = $( this ), $submit = $form.find( 'button[type="submit"]' ), fotoadjunta_value = selectedEncodedFotoAdjunta, url = $form.attr('action');

    var posting = $.post( url, { 
        foto: fotoadjunta_value,
     });

Then I go to my PHP code selected for the form, reached it correctly at first.

Variable base64 code seems like this: "data%3Aimage%2Fjpeg%3Bbase64%2CiVBORw0KGgoAAAANS..." Complete base64 encoded image is here: https://justpaste.it/ft5rd

$extension = "jpeg";
if (!empty($foto)){
    $base64img = rawurldecode($foto);
    
    if (str_contains($base64img, 'data:image/jpeg')) { 
        $extension = "jpeg";
        $base64img = str_replace('data:image/jpeg;base64,', "", $base64img);
        
    } else if (str_contains($base64img, 'data:image/jpg')) {
        $extension = "jpg";
        $base64img = str_replace('data:image/jpg;base64,', "", $base64img);
        
    } else if (str_contains($base64img, 'data:image/png')) {
        $extension = "png";
        $base64img = str_replace('data:image/png;base64,', "", $base64img);
    } 
    
    $filename = '../Imagenes/temp_viajes.'.$extension;
    $fpc = file_put_contents($filename, $base64img);
        if ($fpc) { echo 'Image uploaded correctly'; }

}

But when I go to the folder with the image, i get this:

enter image description here

I tried too, to use base64_decode function instead of rawurldecode, but anyway is the same. Could you help me with this? I don't know what is happening, sincerely.

I tried to download the image into a local folder, but couldn't do it correctly.

1

There are 1 best solutions below

1
Ion Bazan On BEST ANSWER

The image data you are trying to store is base64-encoded. You correctly URL-Decoded and stripped the data prefix, but missed the base64_decode part.

Try changing your second last line to:

$fpc = file_put_contents($filename, base64_decode($base64img));

Please note that you should perform additional validation for any data coming from the user or a form as it is easy to exploit it.