How to Handle Spaces in Data URIs During File Conversion in PHP?

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

How to Handle Spaces in Data URIs During File Conversion in PHP?

How to Convert Data-URI to a File in PHP

When attempting to save a data URI received from JavaScript using PHP, using the following code might result in a corrupted image file:

<code class="php">$data = $_POST['logoImage'];
$uri = substr($data, strpos($data, ",") + 1);
file_put_contents($_POST['logoFilename'], base64_decode($uri));</code>
Copy after login

The underlying reason is the presence of spaces in the data URI that need to be converted to plus signs.

Solution:

The PHP documentation suggests that for data derived from a Javascript canvas.toDataURL() function, spaces should be replaced with plus signs before decoding.

<code class="php">$encodedData = str_replace(' ', '+', $encodedData);
$decodedData = base64_decode($encodedData);</code>
Copy after login

Incorporating this modification into the original code should successfully save the image file:

<code class="php">$data = $_POST['logoImage'];
$uri = substr($data, strpos($data, ",") + 1);
$encodedData = str_replace(' ', '+', $uri);
$decodedData = base64_decode($encodedData);
file_put_contents($_POST['logoFilename'], $decodedData);</code>
Copy after login

The above is the detailed content of How to Handle Spaces in Data URIs During File Conversion 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!