Reputation: 336
my problem:
I am saving an uploaded base64 string to a file using PHP. This string comes from an iPhone app and is a base64 encoded jpeg file.
When I take the contents of this file and add it manually to a data src in an image tag, it displays CORRECTLY. When I read it using file_get_contents and add the resulting string to an img data tag, it works CORRECTLY.
My issue: when I read the file using file_get_contents and save the results using base64_decode(), the resulting jpeg file is INVALID.
My question is, why does the obviously valid base64 encoded string not yield a valid JPEG file when decoded and saved?
Some source excerpts:
This functions as it should, outputs the image:
$imagepath = "D:\\path\\to\\image\\mybase64image.txt";
$imagecontent = file_get_contents($imagepath);
header("Content-type:text/html");
$d = '<img alt="" src="data:image/jpeg;base64,' . $imagecontent . '"/>';
echo $d;
This, does NOT work and the file is invalid:
$imagepath = "D:\\path\\to\\image\\mybase64image.txt";
$imagecontent = file_get_contents($imagepath);
file_put_contents('img.jpg', base64_decode($imagecontent));
-- img.jpg is an invalid file. The paths are valid, the file is there, permissions are there as well (the resulting file img.jpg is a binary file, just invalid) and as I said, it works as a data src.
Here is the base64 encoded file:
http://www.mailnet.de/7E072017-DAEB-41E1-B02E-23FB51A05B80.txt
Any help is appreciated.
Upvotes: 1
Views: 1344
Reputation: 16709
%
characters are not allowed in the b64 set. It looks like your string is url-encoded. urldecode()
it before passing it to base64_decode()
.
It works in the browser like it is because they always decode url attributes.
Upvotes: 1