构建图像上传/调整大小脚本

I'd like to learn how to build my own basic script to upload/resize and rename an image.

Right now I'm using dropzone.js for the client-side code, but I'm struggling for the server-side.

Here is what my upload.php script looks like right now (from a dropzone tutorial):

<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'user/avatar';
if (!empty($_FILES)) {
    $tempFile = $_FILES['file']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $ds. $storeFolder . $ds;
    $targetFile =  $targetPath. $_FILES['file']['name'];
    move_uploaded_file($tempFile,$targetFile);
}
?>

It's working fine, the image gets uploaded where I want, exept I don't understand how it works, and that may be problem for the next steps of my script.

  • What is $_FILES['file']['tmp_name'] exactly ? Why is it not directly $_FILES['file']['name'] ?

  • How does move_uploaded_file($tempFile,$targetFile); ? Why does it need $tempFile ?

  • What's the difference between $_FILES['file'] and $_FILES['image'] ?

  • Last question, what is the best approach now to set-up a basic resizing function ? My goal is to resize the image to 150*150px no matter its original size.

Hopefully I can get some help to figure out all this,

Thanks !

From what I understand, this is a Linux security thing. Linux uploads the file to a temporary folder, and only after it's done can it move the file from where it's uploaded to where you're wanting it to go. That's why you have to do the multiple steps.

As for resizing an image, I don't think you can do this directly. I think you have to use imagecopyresized(). http://php.net/manual/en/function.imagecopyresized.php