PHP base64 encoded image not displaying correctly - php

I'm trying to send an image (any size) over to an API I'm creating, using base64 encoding. The encoded string hits my API as a parameter in the URL. The API built with PHP.
Once the request hits my API, I want to store the image onto my server, and save the file name in the database. This is working, however I'm getting some odd outputs with the actual image.
For reference, I also followed http://blog.justin.kelly.org.au/simple-base64-encodedecode-url-safe-functions/ but have the same results.
The image I am trying to store on my server:
$encode = base64_encode(file_get_contents($image));
echo $encode;
For testing, the ouput of this is the string I'm using to pass to my API.
In the API:
$image = base64_decode($_POST['image']));
$image_name = md5($image) . ".jpg";
file_put_contents(/public/image/ . $image_name, $image);
This works, my image is put onto the server in the correct directory with a random name which is saved to the database.
However, when navigating to the image directly, the image is warped:
If you have a sharp eye, the top part of the image is actually correct before it starts to fail, which makes me start to think whether the string is not getting encoded correctly to be sent as a parameter?
Any clues would be lovely, cheers.
EDIT: Changed it to POST, removed urlencode/decode & removed strtr.

Thanks to the comments:
base64_encode(file_get_contents($image_path));
No urlencode or strtr needed. Use POST request, and alter the post_max_size on the web server to allow for bigger images to be passed through.
$image = base64_decode($this->getParameters('avatar'));
$image_name = md5($image) . ".jpg";

Maybe I'm looking at it wrong, but first you encode it base64 -> urlencode and then you decode it base64 -> urldecode again, shouldn't the latter be in reverse order?

Related

There's any way to put an image from a string (with the contents of an image) in html?

So what I want to do is to write a txt with text and image contents, and then put it in a webpage from the string (with php).
Read the file with php and get a line of the content of the txt to transform it to an image and be able to put it on an html tag.
I haven't tried anything yet, because I don't really know how to do this, or even if it's possible.
Possible duplicate: I think that it isn't because I didn't know what Base64 was so that other answer you were supposed to know it, so for doing it easier to search for people I think it's better to leave it (or not I don't really care so much).
php:
$path = <path to file>;
echo '<img src="data:' . mime_content_type($path) . ';base64,' . base64_encode(file_get_contents($path))" alt="alt_text">';
html:
<img src="data:<mime>;base64,<base64 byte data string>" alt="alt_text">
you can set an image tag to hold raw image byte data, it just has to be in base64 format.
the data:<mime>; part holds the mime, or file content type.
the base64,<base64 encoded string> holds the raw data from the image that you get from using file_get_contents($path) and then encoded in base64 format with base64_encode() function

Base64Decode to file - whats missing?

I have in base64 encoded string in a $_POST field $_POST['nimage'] if I echo it directly as the src value in an img tag, i see the image just fine in browser: echo "<img src='".$_POST['nimage']."'>";
Now, I'm obviously missing a step, because when I base64_decode the string and write it to a file locally on the server, an attempt to view the created file in browser states error:
"The image 'xxxx://myserversomewhere.com/images/img1.jpg' cannot be displayed because it contains errors"
My decode and file put are:
$file = base64_decode($_POST['nimage']);
file_put_contents('images/'. $_POST['imgname'], $file);
which results in images/img1.jpg on the local server. What am I doing wrong in the decode here? Although the base64 output doesn't appear to be URLencoded I have tried urldecode() on it first before base64_decode() just for safe measure with same results.
First few lines of the base64 encode is:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAF4AqsDAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD2gJt+XPJPUGv2A/NB2044oAdtY9M8ccCgB6r8+0jtSYDxEW4xz2qQFCnGOPQ0AAQDJIz9KAF8rI6/hQA9Y+SBgjHIqWA5Yxz2xUsBwUdAMdzSAcFGAB0NADgCVK/KB/OgB6BNzc49agse2OgX2BFZvcCRUO7g
The data you're decoding has a data URI header attached:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...
The header is use by the browser to identify the file type and encoding, but isn't part of the encoded data.
Strip the header (data:image/jpeg;base64,) from the data and base64 decode the rest before writing it to a file: you should be good to go.
$b64 = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...';
$dat = explode(',' $b64);
// element 1 of array from explode() contains B64-encoded data
if (($fileData = base64_decode($dat[1])) === false) {
exit('Base64 decoding error.');
}
file_put_contents($someFileName, $fileData);
NB: Check the return value of your call to base64_decode() for false and abort somehow with a message. It will trap any problems with the decoding process (like not removing the header!).

php image uploading safety against hackers

how safe the following code is, in case everybody could make use of it:
$file = $_FILES["file"]['tmp_name'];
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
<img src="data:image/png;base64,'.$base64.'">
in case this is not safe agains hackers, etc. how should i secure it?
Char set of a base64 encoded string is ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx yz0123456789+/ and an = sign as a last byte filter.
So no matter what the file contents is, you are putting its base64 encoded value and even without escaping, browser will show the given string in the img tag.
You will however need to make sure that the string actually encodes to an image.
And by the way, you are wasting a lot of your server memory for this task by assigning a new variable in every step.

Coverting Hex to Image in PHP?

I am developing mobile app which talks with server via PHP Webservice. This is my first time using PHP. I managed to upload data in to database. Now i need to send an image to store it in ftp server. For that i converted image->hex and sent from my app.
Server Side
I got the hex code but not sure how to convert it in to an image and store in in ftp server. I am really struggling here. I googled it but couldn't find exact one.
Any help is much appreciated.
Convert the HEX string to binary:
$binary = pack("H*", $hex);
pack("H*", ...) is equivalent to hex2bin, which is available since PHP 5.4.
Write it to disk:
file_put_contents("file.png", $binary);
Suppose you have received a hex string in a page where you want to convert this hex to real image. Please check this code snippet will help you or not.
<?php
$hexpic=".......................
.....................";
# convert the hex string to binary
$data = pack("H" . strlen($hexpic), $hexpic);
#write the binary string into an image file
file_put_contents("sample.png", $data);
?>

How to save a base64 decoded image in the filesystem using php?

I am getting a base64 encoded JPEG string via a POST request to my web service.
I want to decode it and save it in the filesystem.
How can I achieve this using PHP 5.3.
I am able to successfully decode the data using the base64_decode function.
How can I save this decoded string as a JPEG image in the server?
Thanks in advance.
If you are sure the image will always be jpg then you can simply use: file_put_contents();
<?php
$decoded=base64_decode($encodedString);
file_put_contents('newImage.JPG',$decoded);
//leave it to you to randomize the filename.
?>
Replacing the blank spaces with + signs is required if the data is derived from canvas.toDataURL() function.
$encodedString = str_replace(' ','+',$encodedString);
See this question
It helped a lot in my case.

Categories