How do I use imagejpeg() with $_FILES["file"]["tmp_name"]

Viewed 83

My TensorFlow project only accepts JPEG because that is what I trained it on. I use a PHP image upload form to post the image. Here is how the image is received by the PHP file and is then used in my Python script.

 $uploaded_file = $_FILES["file"]["tmp_name"];
  move_uploaded_file($_FILES["file"]["tmp_name"], "/tmp/classify-img");

 $output = shell_exec("/usr/bin/python3 /var/www/html/classify.py /tmp/classify-img");

I have used imagejpeg() in the past to convert any picture file extension to .jpeg

When I try this it just won't work though.

$uploaded_file = imagejpeg($_FILES["file"]["tmp_name"]);
  move_uploaded_file($_FILES["file"]["tmp_name"], "/tmp/classify-img");

Good job helping me. Thank you.

Updated & Working Code

#move the uploaded file somewhere temporary
$uploaded_file = $_FILES["file"]["tmp_name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "/tmp/classify-img");

#Is WEBP image?
if (exif_imagetype("/tmp/classify-img".$_FILES["tmp_name"]) == IMAGETYPE_WEBP) {

    //create from webp temp image to be converted
    $im = imagecreatefromwebp("/tmp/classify-img".$_FILES["tmp_name"]);

    // Set the content type header - in this case image/jpeg
    header('Content-Type: image/jpeg');

    // Output the image
    imagejpeg($im, "/tmp/classify-img".$_FILES["tmp_name"], 100);
}

$output = shell_exec("/usr/bin/python3 /var/www/html/classify.py /tmp/classify-img");

The problem was as mentioned below in the comments when you use $_FILES["tmp_name"] it gives you the file temporary file name when you use $_FILES["file"]["tmp_name"] you get the tmp/ part added to your files path.

Thank you for the help everyone. Future readers I hope this helps explain how temporary files work with $_FILES and how to check for pictures and how to convert it to a JPEG without saving it to disk.

1 Answers

Because a common way to handle temporary files is to create the file, open it, and then unlink/delete it without closing the handle. This gives you the ability to use disk while ensuring that the files are deleted/unlinked when the process ends. That is what is happening, why move_uploaded_file() exists at all, and why you must use it before any other operation on that file.

There is also the additional layer of "do you actually want this file to really exist?" because otherwise anyone can POST to any PHP script and have files created in the filesystem.

TLDR: You must use move_uploaded_file() before attempting to use the file.

Related