damaged file during upload with file_put_contents - php

I try to upload an image in a directory using file_put_contents,The file is uploaded but it is damaged and I can not open it. here is my code :
define('UploadDir','../Dir/images');
$path = "image.png";
$data="..."; //image base64 string
$file = UploadDir ."/". $path;
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';

$data="..."; //image base64 string
Assuming $data contains what the comment says, if you put a base64 string in an image it will obviously not be a valid image - it will be a file containing a base64 encoded string.
To be valid (or have a chance at being valid) decode the string before writing it to the file:
$data="..."; //image base64 string
$file = UploadDir ."/". $path;
$success = file_put_contents($file, base64_decode($data));

Is the directory ../Dir/images chmoded to 777? sometimes php won't allow you to access directories if they don't have enough permission.
Try to see if it has enough permissions, if not, then set it to 777 and try it.

Related

Error 403 on writing base64 on file with php

I'm trying to decode a base64 string and write it to a file:
<?php
// requires php5
define('UPLOAD_DIR', '/images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
But the server gives this error message:
403 Forbidden
You don't have permission to access testupload.php on this server
I have set all permissons for the php file and the images directory, so I don't understand why I get this error.
When I put the decoded string of image directly inside the $img variable, it works and it creates the file under the images folder... But when I try to post the decoded string it doesn't work.
How can I solve this?
NOTE :
when we try to send decoded string of image it may contain some virus or something like that from hackers ... i contact with my host providers and they say if you want we can turn of the modsecurity but its really unsafe way to do ... so what i have to do with this situation?

How to encode the image file in PHP

i am using one file upload form field,from that field i want to encode the filename,don't to want to move the any temporary folder,directly i want to insert the database,while display the image directly fetch DB and display the website,I want encode like data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA
$path = basename($_FILES['file']['name']);//here i am getting filename
$im = file_get_contents($path);//here i am getting false
$imdata = base64_encode($im); // so can't here encode the filename
$horoscope = array("encode" => $imdata,"path" =>$path,"getcontents" =>$im);
echo json_encode($horoscope);
PHP uploads the file into a temporary file and tells you where that is in the $_FILES['file']['tmp_name'] the $_FILES['file']['name'] holds the file name that the user called the file on their system, the one they select in the browser.
So if you want to grab the file before you have done a move_uploaded_file() on the file use $_FILES['file']['tmp']
$path = $_FILES['file']['tmp_name'];
$im = file_get_contents($path);
$imdata = base64_encode($im);
$horoscope = array("encode" => $imdata,
"path" =>$path,
"getcontents" =>$im
);
echo json_encode($horoscope);
I was not sure what you were passing back the $path for, so that may still need to be $_FILES['file']['name'].
$horoscope = array("encode" => $imdata,
"path" => $_FILES['file']['name'],
"getcontents" => $im
);
RE:Comment 1
I assume you want to store the base64encoded version of the file to the database so that will be $imdata
RE:Comment 2
To get the extension of the incoming file use pathinfo()
$path = $_FILES['file']['tmp_name'];
$file_parts = pathinfo($path);
$extn = $path_parts['extension'];
But beware, just because the extension says .png is not actual guarantee that it is a .png file

Uploading a base64 image as an image file

So I'm receiving an image in base64 encoding. I want to decode the image and upload it in a specific directory. The encoded file is an image and I'm using $file = base64_decode($base64_string); to decode it. Uploading it via file_put_contents('/uploads/images/', $file); always results in failed to open stream: No such file or directory error.
So, how do I take the decoded string, and upload it on a specific path?
Thanks.
Your path is wrong.
/uploads/images
is checking for a folder in the / directory called uploads. You should specify the full path to the folder:
/var/www/vhosts/MYSITE/uploads/images
I had the same problem and finally solved using this:
<?php
$file = base64_decode($base);
$photo = imagecreatefromstring($file);
//create a random name
$RandomStr = md5(microtime());
$name = substr($RandomStr, 0, 3);
$name .= date('Y-m-d');
$name .= '.jpg';
//assign name and upload your image
imagejpeg($photo, 'images/'.$name, 100);

Retrieving external image and saving locally results in distorted image

Stuck on this one. I have this function below that simply takes $ImageSrc which is an external image from anywhere, eg imgur, and then saves it locally (this is not a scraper, I'm allowing people to attach images to their profiles)
public function UploadScreenshot($ImageSrc, $Title, $Description = false) {
$RandomName = substr(md5($Title . time()), 0, 20);
$UploadDir = "/home/vanrust/public_html/Screenshots/";
$file = pathinfo($ImageSrc);
$ext = $file["extension"];
if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");
$RandomName = "{$RandomName}.{$ext}";
$image = file_get_contents($ImageSrc);
file_put_contents($UploadDir . $RandomName, $image);
}
The result of the file no matter what is unrecognizable.
The image:
After UploadScreenshot() has retrieved it:
Try to use rename() to move the original file to the new location and rename it.
$file = pathinfo($ImageSrc);
$ext = $file["extension"];
if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");
$RandomName = "{$RandomName}.{$ext}";
rename($UploadDir . $RandomName, $ImageSrc);
}
Alternatively, you can use move_uploaded_file() if your $ImageSrc does contain a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism).
file_put_contents() needs to be used with caution. A single offset (in binary codes) at the beginning or at the end of the file will significantly alter the picture. It requires a validation at the end to compare both files bytes.

restore base64_encode image to a file system from database

I'm saving some of my image in to mysql database using base64_encode.
now I want to restore them back to file system.
How can I do that?
Edit...!
Ok, I did not explain enough.
I use this code to encode my image and save them in to a blob table:
function base64_encode_image ($imagefile) {
$imgtype = array('jpg', 'gif', 'png');
$filename = file_exists($imagefile) ? htmlentities($imagefile) : die('Image file name does not exist');
$filetype = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($filetype, $imgtype)){
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
} else {
die ('Invalid image type, jpg, gif, and png is only allowed');
}
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
and use this code to show my image in browser:
if (!isset($_GET['id']) && !ctype_digit($_GET['id'])){
die('Error');
} else {
require_once( addslashes(dirname(dirname(__FILE__)) . '/config.php') );
require_once( addslashes(dirname(__FILE__) . '/Functions.php'));
$row = mysql_fetch_array(mysql_query ("SELECT `id`,`cover_small` FROM `om_manga` WHERE `Active` = '1' AND `id` = '".sql_quote($_GET['id'])."'"));
if (isset($row['id'])){
header("Content-type: image/jpeg");
readfile($row['cover_small']);
} else {
die('Error');
}
}
Now i want them back to a jpg file.
The size of all those image are less then 3kb.
Use PHP's base64_decode() function to convert the encoded data back to binary.
Since base64_decode returns a string, you can use file_put_contents() to write the decoded contents to a file.
It makes me wonder why you're storing the image base64 encoded if you're not using it in that format. You could just as easily store the image in binary format in a binary blob column.
Base64 encoding adds a 33% character overhead (not bytes).
Edit for revised question
The answer to your second question is subjective without context. Without knowing the details of your system, I can't recommend whether you should extract the images.
Decode it the same way you encoded it...
base64_decode()
You might want to store the file extension of the image when writing it to the database so that you can restore it accurately. Just concatenate the new name with the existing extension.
What you should so is something similar to this :
// Retrieved values from database
$encodedImg = $sqlResult['encoded_img'];
$ext = $sqlResult['encoded_img_ext'];
// Concatenate new file name with existing extention
// NOTE : This parameter is a full path. Make sure that the folder
// you are writing the file to has the correct permissions allowing the
// script write access.
$newImagePath = "/some/path/on/the/servers/filesystem/";
$newImageName = $newImagePath."decoded_image.".$ext;
// Saving the decoded file with the new file name.
file_put_contents($newImageName, base64_decode($encodedImg));

Categories