[PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8]
move_uploaded_file — Moves an uploaded file to a new location
Description
move_uploaded_file[string $from
, string $to
]: bool
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.
Parameters
from
The filename of the uploaded file.
to
The destination of the moved file.
Return Values
Returns
true
on success.
If from
is not a valid upload file, then no action will occur, and move_uploaded_file[] will return false
.
If from
is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file[] will return false
. Additionally, a warning will be issued.
Examples
Example #1 Uploading multiple files
Notes
Note:
move_uploaded_file[] is open_basedir aware. However, restrictions are placed only on the
to
path as to allow the moving of uploaded files in whichfrom
may conflict with such restrictions. move_uploaded_file[] ensures the safety of this operation by allowing only those files uploaded through PHP to be moved.
Warning
If the destination file already exists, it will be overwritten.
See Also
- is_uploaded_file[] - Tells whether the file was uploaded via HTTP POST
- rename[] - Renames a file or directory
- See Handling file uploads for a simple usage example
Yousef Ismaeil Cliprz ¶
9 years ago
Security tips you must know before use this function :
First : make sure that the file is not empty.
Second : make sure the file name in English characters, numbers and [_-.] symbols, For more protection.
You can use below function as in example
Third : make sure that the file name not bigger than 250 characters.
as in example :
Fourth: Check File extensions and Mime Types that you want to allow in your project. You can use : pathinfo[] //php.net/pathinfo
or you can use regular expression for check File extensions as in example
#^[gif|jpg|jpeg|jpe|png]$#i
or use in_array checking as
Fifth: Check file size and make sure the limit of php.ini to upload files is what you want, You can start from //www.php.net/manual/en/ini.core.php#ini.file-uploads And last but not least : Check the file content if have a bad codes or something like this function //php.net/manual/en/function.file-get-contents.php. You can use .htaccess to stop working some scripts as in example php file in your upload path. use : AddHandler cgi-script .php .pl .jsp .asp .sh .cgi Do not forget this steps for your project protection.
You have multi choices to checking extensions and Mime types.
Options -ExecCGI
Dan Delaney ¶
13 years ago
For those using PHP on Windows and IIS, you SHOULD set the "upload_tmp_dir" value in php.ini to some directory around where your websites directory is, create that directory, and then set the same permissions on it that you have set for your websites directory. Otherwise, when you upload a file and it goes into C:\WINDOWS\Temp, then you move it to your website directory, its permissions will NOT be set correctly. This will cause you problems if you then want to manipulate that file with something like ImageMagick's convert utility.
Juliano P. Santos ¶
3 years ago
For those which will use inotify-tools to start an event when move_uploaded_file put the file in a specific directory, be aware that move_uploaded_file will trigger the create event, and not the move event of inotify-tools.
Florian S. in H. an der E. [.de] ¶
14 years ago
move_uploaded_file [on my setup] always makes files 0600 ["rw- --- ---"] and owned by the user running the webserver [owner AND group].
Even though the directory has a sticky bit set to the group permissions!
I couldn't find any settings to change this via php.ini or even using "umask[]".
I want my regular user on the server to be able to "tar cjf" the directory .. which would fail on files totally owned by the webserver-process-user;
the "copy[from, to]" function obeys the sticky-bit though!
Zarel ¶
16 years ago
nouncad at mayetlite dot com posted a function that uploaded a file, and would rename it if it already existed, to filename[n].ext
It only worked for files with extensions exactly three letters long, so I fixed that [and made a few other improvements while I was at it].
nlgordon at iastate dot edu ¶
15 years ago
Just a helpful comment. If you have open_basedir set then you must set upload_tmp_dir to somewhere within the open_basedir. Otherwise the file upload will be denied. move_uploaded_file might be open_basedir aware, but the rest of the upload process isn't.
mancow at macfilez dot net ¶
16 years ago
To nouncad at mayetlite dot com,
That function will work fine for files with a 3-character file extension. However, it is worth noting that there are valid, registered file extensions that are longer than 3 characters. For example, a JPEG file can be denoted by *.jpg [and others], but it can also have *.jpeg as a valid extension. Check out //www.filext.com/ for a good reference of file extensions.
The best bet to me would be parsing the uploaded file's name [$_FILES['uploadedfile']['name']] based on the presence of dots. Another wrench in the gears: a file can have dots in the filename. That's easy enough to handle -- just explode[] the file name and hope that the last element in the array it gives you is the file extension [you can always validate it if you're so inclined]. Then just piece it together in a string accordingly by stepping through the array [don't forget to add those dots back to where they were!], appending a guaranteed unique string of characters [or enumerate it like you were doing, keeping track via a loop], and finally tacking on the file extension.
You may have other mechanisms for verifying a file's extension, such as a preg_match on the whole name, using something like "/\\.[gif|jpg|jpeg|png|bmp]$/i" [more can, of course, be added if you so desire] for the most common types of images found on the web.
For blindly guaranteeing an uploaded file will be uniquely named, this seems like a fantastic way to go. Enjoy!
jest3r at mtonic dot net ¶
16 years ago
It seems that move_uploaded_file use the GROUP permissions of the parent directory of the tmp file location, whereas a simple "copy" uses the group of the apache process. This could create a security nighmare if your tmp file location is owned by root:wheel
Harmor ¶
15 years ago
the dot only dot storm at gmail dot com wrote:
>
> In addition to the file extension checking. A simply way
> of getting the extension [regardless of size]:
>
> $efilename = explode['.', $filename];
> $ext = $efilename[count[$efilename] - 1];
>
How about:
$ext = end[explode['.',$filename]];
ccbsschucko at gmail dot com ¶
4 years ago
marcelwoo ¶
10 years ago
One more thing I want to mention about the post_max_size setting in php.ini that nobody else has mentioned.
If you try to upload a file larger than the post_max_size value [or multi files], the page will only refresh itself and no errors are thrown. It took me a while to figure the reason out.
Anonymous ¶
15 years ago
If you find that large files do not upload in PHP even though you've changed the max_upload_size , this is because you need to change the max memory size varible too. The entire file is loaded into memory before it is saved to disk.
labsy at seznam dot org ¶
11 years ago
A note for PHP on Windows IIS platform:
PHP does obviously not like directory traversing among partitions, so if you set upload_tmp_dir to be on different partition as php-cgi.exe or php.exe is, upload_tmp_dir will NOT be accessible for file uploads! You will get ERROR 6 on any attempt to upload file, and file size will be 0.
Resolution is to have upload_tmp_dir set to a path under PHP install folder.
...and make sure this folder [and also session_save_path folder] has at least read/write permissions granted to AppPool owner [usually NETWORK SERVICE] and IIS web user [by default IUSR_].
ineedmynetwork.com ¶
16 years ago
Microsoft returns image/pjpeg not image/jpg when using $_FILES['imageName']['type'];
brentwientjes at NOSPAM dot comast dot net ¶
12 years ago
I have looked at a lot of the file upload code listed below and other php documentation and have developed hopefully a robust single file upload routine. I will later update with a multi file upload. I have modestly tested the code.
I use $isFile and $isMove later in the code for error recording.
Make sure your system has the appropriate file loading limits. This caused a lot of headeaches trying to figure out why some files loaded and some did not. In my case I have an .htaccess file in the root of the web site with:
php_value post_max_size 16M
php_value upload_max_filesize 6M
You may also need to extend the execution time depending upon the amount of data being transferred.
[sorry if spacing of code is a little off. it was hard to make the note editor like the code style.]
Mark Kazemier ¶
14 years ago
I have the same problem as the person two comments below me. When I use the move_uploaded_file function the permissions for the file are set to 0600. No matter what configurations you set.
I searched the internet and I found more people with the same problems, but no solutions. I set the umask of apache to 013 and still the files were set to 0600.
The copy function solves the problem. Another way to solve this problem is using the chmod function after uploading.
bogusred ¶
15 years ago
If you have a directory in a *nix environment where you store all of your file uploads and your php script only seems to work when permissions for that directory are set to 777, here's how to fix it so that you can have the security benefits of 755 while still allowing your php scripts to work, including the move_uploaded_file[].
through shell access, navigate to the directory that contains your uploads folder and run the following 2 commands:
chown -R nobody uploaddir
chmod -R 755 uploaddir
Replace 'uploaddir' with the name of your uploads directory. The first command changes the owner of the directory and files to 'nobody' which is what php operates under. The second changes the folder and files to only allow user access to writing. This is much more secure.
Hopefully this will help someone out there who had the same problem as me.
gotrunko at hotmail dot com ¶
12 years ago
This function can upload many files whitout parameters in the declaration.
If one of them can not be uploaded, the function returns false and deletes all files that have been sent
To use this function you must specify an array with min two parameters like that.
NAME is an optional parameter !
uploadFiles[array["FILES","DESTINATION","NAME"]];
mikelone ¶
17 years ago
If the user try to upload a too bigger file then the upload procedure will fail even if u have established an error message.
How to avoid this problem? there's my solution:
[max_file_size = 2,50 MB]
$fsize = $_FILES["userfile"]["size"];
if[$fsize == 0 || $fsize > 2621000] exit["keep the filesize under 2,50MB!!"];
When the size is bigger than the MAX_FILE_SIZE field, the value of $fsize is equal to 0 [zero] ......
wilcobeekhuizen at gmail dot com ¶
11 years ago
When uploading a file with a very long filename, for example 255 characters, move_uploaded_file fails. The longest file I've succesfully uploaded has a 247 character filename. So, although you can create a 250 character filename locally the server may not be able to move it.
Tom ¶
7 years ago
Nowhere does it say how to get the error/warning message when this fails.
The only way I know of doing it is something like this:
FILE UPLOADED TO: $target_file MOVE UPLOADED FILE FAILED! if [move_uploaded_file[$_FILES["file1"]["tmp_name"], $target_file]] {
echo "
} else {
echo "
print_r[error_get_last[]];
}
Ray.Paseur sometimes uses Gmail ¶
12 years ago
You can only move the uploaded file once. You can use copy[] if you need the file in more than one place.
Send this file:
espiao at gmail dot com ¶
17 years ago
/**
* This function moves the archives and directoryes of a directory of
* origin for a directory destination being able replace them or not.
**/
function mvdir[$oldDir, $newDir, $replaceFiles = true] {
if [$oldDir == $newDir] {
trigger_error["Destination directory is equal of origin."];
return false;
}
if [![$tmpDir = opendir[$oldDir]]] {
trigger_error["It was not possible to open origin directory."];
return false;
}
if [!is_dir[$newDir]] {
trigger_error["It was not possible to open destination directory."];
return false;
}
while [[$file = readdir[$tmpDir]] !== false] {
if [[$file != "."] && [$file !== ".."]] {
$oldFileWithDir = $oldDir . $file;
$newFileWithDir = $newDir . $file;
if [is_dir[$oldFileWithDir]] {
@mkdir[$newFileWithDir."/", 0777];
@mvdir[$oldFileWithDir."/", $newFileWithDir."/", $replaceFiles];
@rmdir[$oldFileWithDir];
}
else {
if [file_exists[$newFileWithDir]] {
if [!$replaceFiles] {
@unlink[$oldFileWithDir];
continue;
}
}
@unlink[$newFileWithDir];
@copy[$oldFileWithDir, $newFileWithDir];
@chmod[$newFileWithDir, 0777];
@unlink[$oldFileWithDir];
}
}
}
return true;
}
/**
* This is an example of move with replace files on destination folder if
* exists files with the same names on destionatio folder
**/
mvdir["/var/www/example/", "/var/www/other_folder/"];
/**
* This is an example of move without replace files on destination
* folder if exists files with the same names on destionatio folder
**/
mvdir["/var/www/example/", "/var/www/other_folder/", false];
sauron at nospam on morannon dot org ¶
18 years ago
An extension only does not really tell you what type of file it really is. I can easily rename a .jpg file to a .zip file and make the server think it is a ZIP file with webmaster kobrasrealm's code.
A better way is to use the Linux utility "file" to determine the file type. Although I'm aware that some users might use Windows on their webservers, I thought it's worth mentioning the utility here. Using the backtick operators and preg_matches on the output, you can easily determine the file type safely, and fix the extension when necessary.
info at arpadh dot hu ¶
15 years ago
Values upload_max_filesize and post_max_size [ie. php.ini values] cannot be modified in runtime with ini_set[] function.
If you are using Apache web server, use .htaccess files with an IfModule replacing values corresponding to your file size and PHP version:
php_value upload_max_filesize 50M
php_value post_max_size 50M
- means 50MB upload limit.
booc0mtaco at gmail dot com ¶
15 years ago
Also, make sure that the setting for the post_max_size allows for a proper file size range.
post_max_size = 128M ; Expands the size of POST data for file uploads
agan0052 at hotmail dot com ¶
14 years ago