I cannot imagine why should I use this function instead of a simple rename.
The manual writes:
move_uploaded_file
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.
Can you please write an example why is this so important?
Because using regular filesystem functions for this purpose might create security vulnerabilities. If you do this in your program:
rename($source, $destination);
and the attacker is able to control the value of $source
, they have gained the capability to rename (or move! -- rename
also moves files across directories) any file that your PHP process has access to.
If they can also influence $destination
or if there is some way of gaining access to the contents of the file after it is moved they can use this vulnerability to gain access to your source code at the very least, which would usually reveal authentication credentials. And it's not difficult to imagine this happening: if you accept user uploads and make them accessible over a URL this functionality would be already built into your application.
In general, it's a security issue that you have to think about; the _uploaded_file
functions are there to help you land in the pit of success.
Update (material pulled from comments):
Modern handling of file uploads (through $_FILES
) has largely made move_uploaded_file
technically unnecessary. But don't forget that:
- Technically unnecessary might still be a good idea: we are talking security, why not be extra safe?
move_uploaded_files
was introduced at a time where $_FILES
did not even exist and widespread usage of register_globals
was reality instead of a children horror story.
move_uploaded_file
actually moves your uploaded file FROM tmp directory TO permanent location on your server. Yes it's important because you will have to move the file to your server at your specified location right?
Check code snippet example for move_uploaded_file
here:
http://www.developphp.com/view_lesson.php?v=449
You should not use rename function as rename function is used to rename an existing file with a new name. Whereas function like move_uploaded_file and copy are actually used to upload a file from tmp directory to the destination directory.
rename() should be used to move ordinary files, and not files uploaded through a form. The reason for this is because there is a special function, called move_uploaded_file(), which checks to make sure the file has indeed been uploaded before moving it - this stops people trying to hack your server into making private files visible. You can perform this check yourself if you like by calling the is_uploaded_file() function.