Search code examples
phpimagefilecropjcrop

PHP $_FILES Array Manipulation


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?


Solution

  • 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