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