Home  >  Article  >  Backend Development  >  How to Correctly Save Data URIs as Files in PHP

How to Correctly Save Data URIs as Files in PHP

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 08:55:02634browse

How to Correctly Save Data URIs as Files in PHP

Converting Data-URI to a File in PHP

When tasked with saving a data URI obtained from JavaScript, a common issue arises where the resulting image file appears corrupted. This problem often occurs when using code similar to the following:

$data = $_POST['logoImage'];

$uri = substr($data,strpos($data,",")+1);

file_put_contents($_POST['logoFilename'], base64_decode($uri));

To resolve this issue, consult the PHP manual, where you will find the following insight:

"If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:"

$encodedData = str_replace(' ','+',$encodedData);
$decodedData = base64_decode($encodedData);

In this example, the 'encodedData' variable is the data URI string obtained from JavaScript. Replacing the blanks (' ') with plusses (' ') corrects any corruption that may occur during decoding. The decoded data can then be saved successfully using the provided file_put_contents function.

The above is the detailed content of How to Correctly Save Data URIs as Files in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn