9

I am getting a base64 encoded JPEG string via a POST request to my web service. I want to decode it and save it in the filesystem. How can I achieve this using PHP 5.3. I am able to successfully decode the data using the base64_decode function.

How can I save this decoded string as a JPEG image in the server?

Thanks in advance.

Amit
  • 3,644
  • 9
  • 38
  • 49
  • did u try to save this in a binary file using fopen ? – Arfeen Nov 24 '11 at 06:23
  • @Arfeen Thanks, I tried file_put_contents() and it worked. I came here to update my question to notice that your and Lawrence Cherone's comments. – Amit Nov 24 '11 at 07:02
  • As a general solution that is much more flexible and powerful, [PHP-FileUpload](https://github.com/delight-im/PHP-FileUpload/tree/master) comes with both [`Base64Upload`](https://github.com/delight-im/PHP-FileUpload/blob/7c950635cbd45ade9fb2656eb285259dc2a8f0fb/src/Base64Upload.php) and [`DataUriUpload`](https://github.com/delight-im/PHP-FileUpload/blob/7c950635cbd45ade9fb2656eb285259dc2a8f0fb/src/DataUriUpload.php), which are [documented here](https://github.com/delight-im/PHP-FileUpload/blob/master/README.md#usage). – caw Dec 06 '17 at 11:37

2 Answers2

13

If you are sure the image will always be jpg then you can simply use: file_put_contents();

<?php 
$decoded=base64_decode($encodedString);

file_put_contents('newImage.JPG',$decoded);
//leave it to you to randomize the filename.
?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • Thanks a lot. It works. However its not guaranteed to always be a JPEG. I'll try and see if I can get it from the MIME type. :) Appreciate the help! – Amit Nov 24 '11 at 07:06
8

Replacing the blank spaces with + signs is required if the data is derived from canvas.toDataURL() function.

 $encodedString = str_replace(' ','+',$encodedString);

See this question

It helped a lot in my case.

Community
  • 1
  • 1
V.Vachev
  • 341
  • 1
  • 7
  • 20