Home >Backend Development >PHP Tutorial >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!