PHP Data-URI for file

I have a data URI that I get from javascript and try to save using php. I am using the following code which gives an obviously damaged image file:

$data = $_POST['logoImage']; $uri = substr($data,strpos($data,",")+1); file_put_contents($_POST['logoFilename'], base64_decode($uri)); data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs 9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAxklEQVQYlYWQMW7CUBBE33yITYUUmwbOkBtEcgUlTa7COXIVV5RUkXKC5AxU EdyZVD4kyKxkwIrr9vd0c7Oih aopinLNsF6Qkg2XW4XJ7LGFsAAcTV6lF5/jLdbALA9XDAXYfthFQVx OrmqKYK88/7rbbMFksALieTnzu9wDYTj6f70PKsp2kwAiSvjXNcvkWpAfNZkzWa/5a9yT7fdoX7rrB7hYh2fXo9HdjPYQZu3MIU8bYIlW20y0RUlXG2Kpv/vfwLxhTaSQwWqwhAAAAAElFTkSuQmCC 

The code below is the actual image as a data URI. 'logoImage' is the line above, and $ uri is the line minus' image / jpeg; base64, '.

+44
php file-io image data-uri
Jul 18 '11 at 15:33
source share
3 answers

A quick look in the PHP manual gives the following:

If you want to keep the data retrieved from Javascript canvas.toDataURL (), you need to convert spaces to pluses. If you do not, the decoded data will be corrupted:

 <?php $encodedData = str_replace(' ','+',$encodedData); $decodedData = base64_decode($encodedData); ?> 
+59
Jul 18 '11 at 15:39
source share

The data URI that you have in your example is not a valid PNG image. This will never work and is not related to data related code.




Not applicable, but may be of interest:

 file_put_contents($_POST['logoFilename'], file_get_contents($data)); 

Idea: PHP itself can read the contents of a data URI ( data:// ) , so you don’t need to decode it your own.

Note that the official data URI scheme (ref: RFC 2397 "data" URL scheme ) does not include a double slash (" // ") after a colon (" : "). PHP supports with or without two slashes.

  # RFC 2397 conform $binary = file_get_contents($uri); # with two slashes $uriPhp = 'data://' . substr($uri, 5); $binary = file_get_contents($uriPhp); 
+39
Jul 18 '11 at 15:38
source share

All code that works:

 $imgData = str_replace(' ','+',$_POST['image']); $imgData = substr($imgData,strpos($imgData,",")+1); $imgData = base64_decode($imgData); // Path where the image is going to be saved $filePath = $_SERVER['DOCUMENT_ROOT']. '/ima/temp2.png'; // Write $imgData into the image file $file = fopen($filePath, 'w'); fwrite($file, $imgData); fclose($file); 
+17
May 21 '15 at 7:22
source share



All Articles