1

I want to save a base64 string as an image (.png or .jpg) on my server.

The string I get looks like this: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQA[...]"

I tried this:

$data = $_POST['form_new_data'];
        list($type, $data) = explode(';', $data);
        list(, $data)      = explode(',', $data);
        $data = base64_decode($data);
        file_put_contents("/userImgs/pic.jpg",$data);

but it is not working (maybe because the base64 string is a jpeg?).. Please help..

1 Answer 1

7

try this

$data = $_POST['form_new_data'];
file_put_contents('img.jpg', base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data)));
Sign up to request clarification or add additional context in comments.

4 Comments

you forgot stripping the prefix ;-P
realized after posting it. It is fine now rt?
thank you, works, but can you tell me, why mine is not working? I used the code from the accepted answer of this thread: stackoverflow.com/questions/11511511/… @georoot
@user3375021 to be frank i am not sure why explode is being used at all. I would say try to print $data in your script just before you store it to a file and compare it with the output of preg_replace in my script

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.