Home » Php » php – Difference between copy and move_uploaded_file

php – Difference between copy and move_uploaded_file

Posted by: admin July 12, 2020 Leave a comment

Questions:

what is difference between copy() and move_uploaded_file()

I think both the functions perform same operations then whats the difference?

copy ( $_FILES['file']['tmp_name'], 
     "C:/Apache/htdocs/" . $_FILES['file']['name'] ) 


move_uploaded_file($_FILES['file']['tmp_name'], 
     "C:/Apache/htdocs/" . $_FILES['file']['name'])
How to&Answers:

This function checks to ensure that the file designated by filename is
a valid upload file (meaning that it was uploaded via PHP’s HTTP POST
upload mechanism). If the file is valid, it will be moved to the
filename given by destination.

This sort of check is especially important if there is any chance that
anything done with uploaded files could reveal their contents to the
user, or even to other users on the same system.

http://php.net/manual/en/function.move-uploaded-file.php

If filename is not a valid upload file, then no action will occur, and
move_uploaded_file() will return FALSE.

Answer:

Copy will copy the file source to destination whereas move will move it.

When a file is copied, a duplicate is made means temporary buffers(source) is not cleaned.

When you move a file, it is deleted from the original location means in temporary buffer (source: $_FILES) and move the file in destinations.

Answer:

As to complement @Muhammad Hasan Khan’s answer.

According to this comment https://www.php.net/manual/en/function.is-uploaded-file.php#113766, move_uploaded_file does not bring anymore security than is_uploaded_file, and therefore the two followings snippets are strictly equivalent in terms of security:

$tmp = $_FILES['file']['tmp_name'];
if(false === is_uploaded_file($tmp)){
    return false;
}
copy($tmp, $dst);
$tmp = $_FILES['file']['tmp_name'];
move_uploaded_file($tmp, $dst);