I am using a form to upload an image. Upon image upload, we will be able to see the uploaded image. Then I used JCrop (http://deepliquid.com/content/Jcrop.html) to allow cropping for this image. Let's assume I only care about JPEG images. I am then ready to submit the form.
Upon form submission I will perform some image manipulation and crop the image. However I want to put the information for this cropped image back into the $_FILES array (this is a must). How would I go about manipulating this $_FILES array in a PHP script?
Here is what I had attempted and it would not work.
$upload_dir = '/Users/user/Sites/tmp/';
$file_name = $_FILES['image']['name'];
$file_name = "cropped_".$file_name;
$tmp_name = $_FILES['image']['tmp_name'];
$file_size = $_FILES['image']['size'];
$src_file = imagecreatefromjpeg($tmp_name);
list($width,$height) = getimagesize($tmp_name);
// Creates cropped image
$tmp = imagecreatetruecolor($_POST['w'], $_POST['h']);
imagecopyresampled($tmp, $src_file, 0, 0, $_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'], $_POST['w'], $_POST['h']);
$small_pic_file_path = $upload_dir.$file_name;
imagejpeg($tmp,$small_pic_file_path,85);
$message = "<img src='http://localhost/~user/tmp/".$file_name."'>";
$_FILES['image']['name'] = $file_name;
$_FILES['image']['type'] = "image/jpeg";
// unlink($tmp_name);
// if(!move_uploaded_file($upload_dir.$file_name, $tmp_name)) echo "Failure Moving Image";
$_FILES['image']['tmp_name'] = $upload_dir.$file_name;
$_FILES['image']['error'] = 0;
$sizes = getimagesize($upload_dir.$file_name);
$_FILES['image']['size'] = ($sizes['0'] * $sizes['1']);
It is allowable to change this $_FILES array?
Only changing in the global array won't work. You are just saying $_FILES['image']['tmp_name'] will be the newly created one. But the tmp location is having same old file.
But you have to update the image in /tmp folder.
Get your tmp path and copy the image there.
kind of copy($newImage, /tmp) - get your tmp folder path from php.ini
It's not a good idea to change a superglobal you'd better copy it into another variable and after do whatever you want.
Related
I have a certain code for image upload .I found this on the internet and there was no explanation of the code either.What i can understand from the code is that php upload a certain file makes it a temporary file and then moves the temporary file to the original location
Code Looks something like this
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $imagePath . $_FILES["img"]["name"]);
What happens now is that when i try to provide an unique name to the image when it is being moved using the move_uploaded_file then a file does come up inside the folder but it says an invalid file and with the extension type of file.
My code for trying to achieve the same but with an unique name/id for the uploaded image.
$uniquesavename=time().uniqid(rand());
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $imagePath . $uniquesavename);
How to achieve the same as before and could you please explain me the previous code as well?
Sample code:
// Get file path from post data by using $_FILES
$filename = $_FILES["img"]["tmp_name"];
// Make sure that it's a valid image which can get width and height
list($width, $height) = getimagesize( $filename );
// Call php function move_uploaded_file to move uploaded file
move_uploaded_file($filename, $imagePath . $_FILES["img"]["name"]);
Please try this one:
// Make sure this imagePath is end with slash
$imagePath = '/root/path/to/image/folder/';
$uniquesavename=time().uniqid(rand());
$destFile = $imagePath . $uniquesavename . '.jpg';
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $destFile);
Edit 1:
To get image type in two ways:
Get the file type from upload file name.
Use php function as below
CODE
// Get details of image
list($width, $height, $typeCode) = getimagesize($filename);
$imageType = ($typeCode == 1 ? "gif" : ($typeCode == 2 ? "jpeg" : ($typeCode == 3 ? "png" : FALSE)));
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$location = "uploads/";
$new_name = $location.time()."-".rand(1000, 9999)."-".$name;
if (move_uploaded_file($tmp_name, $new_name)){
echo "uploaded";
}
else{
sleep(rand(1,5));
$new_name = $location.time()."-".rand(1000, 9999)."-".$name;
if (move_uploaded_file($tmp_name, $new_name)){
echo "uploaded";
}
else{
echo"failed, better luck next time";
}
}
here, location is folder inside directory, i mainly create folder "uploads"
time() adds timestamp , which is always unique, until two person upload at same time, which is rare.
moreover, adding 4 digit random number to it , making combination rarest
after that adding actual file name , to making combination unique.
why i use it :
u can extract timestamp later if u need to know when image was uploaded.
u can extract actual filename too.
Lets, say our so unique combination somehow fails,
then, php instance will wait for 1 to 5 second whatever random number is generated. and rename with latest timestamp and regenerated random number.
It's the best u can think of without being resource hog.
you can use
$strtotime = strtotime("now");
$filename = $strtotime.'_'.$_FILES['file']['name'];
i have a problem with uploading images into different directory.
$path = "../uploads/";
$path2 = "../uploads2/";
$imagename = $_FILES['photoimg']['name'];
$actual_image_name = $imagename;
$uploadedfile = $_FILES['photoimg']['tmp_name'];
$widthArray = array(600,240); //resize width.
foreach($widthArray as $newwidth)
{
$filename = $uploadedfile,$path,$actual_image_name,$newwidth;
//Original Image
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{}
if(move_uploaded_file($uploadedfile, $path2.$actual_image_name))
{}
i want to upload image into uploads and uploads2 folders also?
for example width width = 600px into uploads, width = 240px into folder upload2.
what's wrong with my code?
After moving the file with move_uploaded_file it isn't available in the location stored in $uploadedfile anymore. For the second file you have to use copy function.
Please try the following:
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{}
if(copy($path.$actual_image_name, $path2.$actual_image_name))
{}
Remove this line. I don't know for what purpose it's there.
$filename = $uploadedfile,$path,$actual_image_name,$newwidth;
To resize the uploaded image use any library to resize it then pass it.
But here is the full code to upload in different directory. But you will have to resize these two $file1 & $file2 to your expected resize file and replace the same in $file1 & $file2
To resize you can use any code suggested here
$path1 = "../uploads/";
$path2 = "../uploads2/";
$file1= $_FILES['photoimg'];
$file2= $_FILES['photoimg'];
$file1_imagename = $file1['name'];
$file2_imagename = $file2['name'];
$file1_actual_image_name = $file1_imagename;
$file2_actual_image_name = $file2_imagename;
$file1_uploadedfile = $file1['tmp_name'];
$file2_uploadedfile = $file2['tmp_name'];
$widthArray = array(600, 240); //resize width.
if (move_uploaded_file($file1_uploadedfile, $path1 . $file1_actual_image_name)) {
echo "Uploaded Successfully!";
}
if (move_uploaded_file($file2_uploadedfile, $path2 . $file2_actual_image_name)) {
echo "Uploaded Successfully!";
}
I need to resize the uploaded image and save it with given resolutions. Assume user uploads just only one single image and I save it like 35x35, 100x100 and 512x512 after finishing the upload. finally his one upload save in my folder as 3 images with different resolutions. I've done up to this point using laravel...
public function postSingleUpload()
{
//create the relevant directory to add the user image
//get the directory name (directory name equals to user id)
$dirPath = sprintf("images/users/avatar/%s/", Auth::user()->id);
//create the directory named by user id
if (!file_exists($dirPath)) {
mkdir($dirPath, 0700);
}
$file = Input::file('image');
//save image with given resulutions
//---- this part i need --------//
}
so please help me for this.
Here is what I have done to save the uploaded image with given resolutions:
//First Copy the uploaded image to some location
Input::file('profilePic')->move('Users/'.$username.'/Wallpics/',$name)
//Set this attribute for quality after resampling
$quality = 90;
$src = 'Users/'.$username.'/Wallpics/'.$name;
//Run this on recently saved uploaded image
$img = imagecreatefromjpeg($src);
//get this values from user by submitting form ( either by crop or by textboxes)
$width=(int)Input::get('w');
$height=(int)Input::get('h');
$x=(int)Input::get('x');
$y=(int)Input::get('y');
//This is the code to resample the image and generate a new to ur requirements
$dest = ImageCreateTrueColor($width, $height);
imagecopyresampled($dest, $img, 0, 0,$x,$y, $width, $height,$width,$height);
imagejpeg($dest, 'Users/'.$username.'/profilePic/'.$name, $quality);
//Set the path in database
$profile->profilePic=asset('Users/'.$username.'/profilePic/'.$name);
$profile->save();
I'm working in my site which is in zen cart, actually a want to add a little functionality on it, and that is.... When I upload a image for a product I also want to create a thumbnail size of that image to be in a folder. Now I tried to search a file where the code to upload image goes on... I found a file in htdocs/admin_folder/includes/modules/new_product_preview.php
Now after getting details from user from a page htdocs/admin_folder/product.php it form post it in new_product_review.php page with a action defined in it and here the code for uploading image I've just simply added code as follows but it is not uploading the image in folder.
I've tried to echo the name of the file, so I've just put the alert for the image name parameters, I'm getting the $_FILES["products_image"]["tmp_name"] as something like, /tmp/gsnVaX.. like but
when I check $_FILES["products_image"]["name"] it gives the correct name of the file...
Why its not putting the image in temporary folder? When I put the resize code on it then it saves image in my folder with the same size which I wanted but whole image is just blank black.
Code is:
$image = "../images/thumbs/anki_".$_FILES["products_image"]["name"];
move_uploaded_file($_FILES["products_image"]["tmp_name"],$image);
and code when I'm doing this through resize is:
$control = "products_image";
$fileName = $_FILES[$control]['name'];
$uploadedfile = $_FILES[$control]['tmp_name'];
echo "<script>alert('".$fileName."');</script>";
$exts = explode(".",$fileName);
$ext = array_pop($exts);
$uploadedfile = $_FILES[$control]['name'];
$extension = $ext;
$extension = strtolower($extension);
if($extension=="jpg" || $extension=="jpeg" )
{
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
$newwidth = 140;
list($width,$height)=getimagesize($uploadedfile);
$newheight=($height/$width)*$newwidth;
$newheight = 135;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "../images/thumbs/". $fileName;
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp);
What am I doing wrong with it?
When i made this function:
function makeThumbnail($type, $name, $size, $tmp_name, $thumbSize) {
//make sure this directory is writable!
$path_thumbs = "uploaded_files/";
//the new width of the resized image, in pixels.
$img_thumb_width = $thumbSize; //
$extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)
//List of allowed extensions if extlimit = yes
$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");
//the image -> variables
$file_type = $type;
$file_name = $name;
$file_size = $size;
$file_tmp = $tmp_name;
//check if you have selected a file.
echo $file_tmp."<br>";
echo $file_name."<br>";
echo $file_type."<br>";
echo $file_size."<br>";
if(!is_uploaded_file($file_tmp)){
echo "Error: Please select a file to upload!. <br>--back";
exit(); //exit the script and don't process the rest of it!
}
//check the file's extension
$ext = strrchr($file_name,'.');
$ext = strtolower($ext);
//uh-oh! the file extension is not allowed!
if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
echo "Wrong file extension. <br>--back";
exit();
}
//so, whats the file's extension?
$getExt = explode ('.', $file_name);
$file_ext = $getExt[count($getExt)-1];
//create a random file name
$rand_name = md5(time());
$rand_name= rand(0,999999999);
//the new width variable
$ThumbWidth = $img_thumb_width;
/////////////////////////////////
// CREATE THE THUMBNAIL //
////////////////////////////////
//keep image type
if($file_size){
if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
$new_img = imagecreatefromjpeg($file_tmp);
}elseif($file_type == "image/x-png" || $file_type == "image/png"){
$new_img = imagecreatefrompng($file_tmp);
}elseif($file_type == "image/gif"){
$new_img = imagecreatefromgif($file_tmp);
}
//list the width and height and keep the height ratio.
list($width, $height) = getimagesize($file_tmp);
//calculate the image ratio
$imgratio=$width/$height;
if ($imgratio>1){
$newwidth = $ThumbWidth;
$newheight = $ThumbWidth/$imgratio;
}else{
$newheight = $ThumbWidth;
$newwidth = $ThumbWidth*$imgratio;
}
//function for resize image.
if (function_exists(imagecreatetruecolor)){
$resized_img = imagecreatetruecolor($newwidth,$newheight);
}else{
die("Error: Please make sure you have GD library ver 2+");
}
//the resizing is going on here!
imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//finally, save the image
ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext", 100);
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
//ok copy the finished file to the thumbnail directory
// move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");
/*
Don't want to copy it to a separate directory?
Want to just display the image to the user?
Follow the following steps:
2. Uncomment this code:
/*
/* UNCOMMENT THIS IF YOU WANT */
echo "OK THUMB " . $thumbSize;
exit();
//*/
//and you should be set!
//success message, redirect to main page.
$msg = urlencode("$title was uploaded! Upload More?");
}
Then it stopped working, but outside a function, it works good.
As you can see i added "echo $file...." because i wanted to see if they have value, and they do have the right values.
I just get the error Error: Please select a file to upload.
This function is running after an normal upload image script(full size).
When i call the function i do:
makeThumbnail($_FILES[$fieldname]['type'], $_FILES[$fieldname]['name'], $_FILES[$fieldname]['size'], $_FILES[$fieldname]['tmp_name'], 100);
At my other file where its not in a function, theres no difference only that the variables is:
$file_type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
But it should work, I cant find anything wrong, but it doesnt and i keep getting that error. If i remove the is_uploaded_file function, i get a bunch of another errors.
Make sure you are not using move_uploaded_file() before calling the function.
I use timthumb to process the image into a thumbnail when it outputs it to screen, instead of when it's uploaded.
It means you only have one file and not one master size and one thumb size. TimThumb reduces the size of the file on serverside so it appears nice and smooth on the browserside. Have a look at it: TimThumb Link