How to Correctly Save Data URIs as Files in PHP

Mary-Kate Olsen
Release: 2024-10-23 08:55:02
Original
631 people have browsed it

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));
Copy after login

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);
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!