PHP: move_uploaded_file - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

parse_ini_file mkdir

Last updated: Fri, 26 Jan 2007

view this page in

# move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5)

move_uploaded_file -- Перемещает загруженный файл в новое место

## Описание

bool move_uploaded_file ( string filename, string destination )

Эта функция проверяет, является ли файл `filename` загруженным на сервер (переданным по протоколу HTTP POST). Если файл действительно загружен на сервер, он будет перемещён в место, указанное в аргументе `destination`.

Если `filename` не является загруженным файлов, никаких действий не предпринимается и move_uploaded_file() возвращает `FALSE`.

Если `filename` является загруженным файлом, но не может быть перемещён по каким-либо причинам, никакие действия не предпринимаются и move_uploaded_file() возвращает `FALSE`. Кроме того, отображается предупреждение.

Такая проверка особенно важна в том случае, если существует шанс того, что какие-либо действия, производимые над загруженным файлом, могут открыть его содержимое пользователю или даже другим пользователям системы.

> Замечание: На move_uploaded_file() не распространяются нормальные UID-ограничения режима безопасный режим. Это не является нарушением безопасности, потому что move_uploaded_file() оперирует лишь теми файлами, которые загружены на сервер через PHP. Функция move_uploaded_file() принимает во внимание как безопасный режим, так и open_basedir. Тем не менее, ограничения накладываются лишь на параметр `destination`, чтобы разрешить перемещение загруженных файлов, так как параметр `filename` может конфликтовать с этими ограничениями. move_uploaded_file() гарантирует безопасность этой операции, работая лишь с теми файлами, которые были загружены через PHP.

Внимание
Если файл `destination` уже существует, он будет перезаписан.

См. также описание функции is_uploaded_file() и раздел Загрузка файлов на сервер для примеров использования этих функций.

add a note User Contributed Notes
move_uploaded_file
Harmor
06-Mar-2007 09:38
`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));`
dev at rising9 dot com
06-Mar-2007 05:07
`Can you explain more, how i can change the max memory size varible for the large file can work with move_uploaded_file()?
Thanks a lot!`
03-Feb-2007 07:32
`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.`
Nibinaear
01-Nov-2006 02:49
`If you want to change the filename used by the user then use this code (static name). This example uploads a pdf magazine to a website and always overwrites the file that is there. Use if you are dealing with a small number of files or people who know what they're doing!
<?php
if(!empty($_FILES["magfile"]))
{
$uploaddir = $_SERVER['DOCUMENT_ROOT']."/dainsider/magazines/";
$uploaddir.="magazine.pdf";
//Copy the file to some permanent location
if(move_uploaded_file($_FILES["magfile"]["tmp_name"], $uploaddir))
{
echo "Magazine Updated!";
}
else
{
echo "There was a problem when uploding the new file, please contact ".$admin_email." about this.";
print_r($_FILES);
}
}
?>`
shacker at birdhouse dot org
10-Sep-2006 12:28
`If you're dealing with files uploaded through some external FTP source and need to move them to a final destination, searching php.net for "mv" or "move" won't get you what you want. You want the rename() function.
http://www.php.net/manual/en/function.rename.php
(move_uploaded_file() won't work, since the POST vars won't be present.)`
Rob Szarka
22-Aug-2006 06:18
`Apparently the warning above might better be written "If the destination file already exists, it will be overwritten ... regardless of the destination file's permissions."
In other words, move_uploaded_file() executes as if it's root, not the user under which the web server is operating or the owner of the script that's executing.`
sergeygrinev at mail dot ru
20-Apr-2006 02:04
`small typo:
$fulldest = $dest.$newfilename;
show be
$fulldest = $dest.$filename;
or you would have infinite loop.`
Zarel
13-Apr-2006 06:12
`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).
<?php
// Usage: uploadfile($_FILE['file']['name'],'temp/',$_FILE['file']['tmp_name'])
function uploadfile($origin, $dest, $tmp_name)
{
$origin = strtolower(basename($origin));
$fulldest = $dest.$origin;
$filename = $origin;
for ($i=1; file_exists($fulldest); $i++)
{
$fileext = (strpos($origin,'.')===false?'':'.'.substr(strrchr($origin, "."), 1));
$filename = substr($origin, 0, strlen($origin)-strlen($fileext)).'['.$i.']'.$fileext;
$fulldest = $dest.$newfilename;
}
if (move_uploaded_file($tmp_name, $fulldest))
return $filename;
return false;
}
?>`
jessy dot diamondman at gmail dot com
05-Apr-2006 09:29
`I am pretty new, and am having upload problems myself, but I think I can help out ffproberen2 at dodgeit dot com with his premission denied errors. I had these two, and I had to change the upload directory, not the tmp_upload_dir or what ever it is called. The move_uploaded_file meathod takes an upload location as the last parameter. I am running a bundled package of Apache, Php, mySQL and so on, and on mine, specifing a directory of '' will upload it into C:\Program Files\xampp\apache (my PC is my experimental server, I will get linux, but got to obtain it and internet cuts off after 196mb so can't download it) even though php file is in C:\Program Files\xampp\htdocs\xampp\jessyexum\upload_client.php.
This is a code that I found and then modified, hope it can help. It dosn't always upload every file type giving me an error #2.
<?php
$uploaddir = '';
$uploadfile = $uploaddir . basename($_FILES['upfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['upfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>`
ffproberen2 at dodgeit dot com
05-Apr-2006 03:02
`On windows I made the directory writable, by changing the Apache httpd.conf file.
The problem I had, was with the upload directory. The move_uploaded_file produced an error like: failed to open stream: Permission denied.
I changed my php.ini to specify an upload directory:
upload_tmp_dir = "d:/temp/php/uploads/"
and I added the following in the Apache hpptd.conf file:
<Directory "D:/temp/php/uploads">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
restarted Apache, and the upload succeeded.`
j dot m dot thomas at NOSPAM dot blueyonder dot co dot uk
16-Feb-2006 12:26
`To retrieve the file extension, and various other information about the path, it is easiest to use the pathinfo function.
<?php
$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
?>
Would produce:
/www/htdocs
index.html
html
http://uk.php.net/manual/en/function.pathinfo.php`
adam at darkhousemedia dot com
02-Feb-2006 10:35
`To retrieve the file extension, I think this example makes more sense than the one below.
$ext = explode(".", $file);
$ext = array_pop($ext);
It doesn't have to count() the array and then subtract 1 to point to the proper array element, it simply isolates the last element of the array, and discards everything else.`
the dot only dot storm at gmail dot com
02-Feb-2006 12:02
`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];
Note:
This is *could* cause a ~0.01s delay because you're not using COUNT() to initialize a variable by itself. Refer to googling similar: php count function performance`
calamitoso at gmail dot com
31-Jan-2006 11:10
`to separate (for example) images from other file types among the uploaded files you can check the MIME type also (thus making the file extension check unnecessary)
$temp = strpos($_FILES["pic"]["type"], "image");
if ($rep===FALSE){
//the strpos function will return a boolean "false" ONLY if the needle string is not found within the haystack
echo "is not an image";
}else{
echo "is an image";
}`
mancow at macfilez dot net
09-Jan-2006 09:31
`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 http://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!`
AT-HE (at_he AT hotm4il DOT com)
15-Dec-2005 10:28
`---------
Note that post_max_size also needs to be considered, by default it is 8M. I raised my upload_max_filesize to 20M and was wondering why 10M uploads weren't working...
r: It could be because of your max execution time.
----------
try changing the value of both post_max_size and upload_max_filesize`
nouncad at mayetlite dot com
14-Dec-2005 05:30
`Great!! my first note here...
This function upload a file.
If file exist, create a copy as "filename[n].ext"
<?php
function subirFichero($origen, $destinoDir, $ftemporal) {
$origen = strtolower(basename($origen));
$destinoFull = $destinoDir.$origen;
$frand = $origen;
$i = 1;
while (file_exists( $destinoFull )) {
$file_name = substr($origen, 0, strlen($origen)-4);
$file_extension = substr($origen, strlen($origen)-4, strlen($origen));
$frand = $file_name."[$i]".$file_extension;
$destinoFull = $destinoDir.$frand;
$i++;
}
if (move_uploaded_file($ftemporal, $destinoFull)) return $frand;
else return "0";
}
?>`
ineedmynetwork.com
07-Nov-2005 01:27
`Microsoft returns image/pjpeg not image/jpg when using $_FILES['imageName']['type'];`
albert
07-Nov-2005 12:44
`move_uploaded_file()'s return codes are not allways obious !
Unable to move '/var/tmp/phpuuAVJv' to '/home/me/website.com/upload/images/hello.png'
will apear if your disk is full, or the webserver (www user) exeeded it's disk qouta. (probably some others)
i dont know if its a bug (just not iplemented) or a feature (to hide from 3rd parties details about the system or about the specific error) ?
it happend to me that after several months of successful operation, the disk filled up and qouta exeeded.
it took me long time, finding out why all the sudden my scripts didnt work properly anymore.`
04-Nov-2005 03:56
`[quote]
Note that post_max_size also needs to be considered, by default it is 8M. I raised my upload_max_filesize to 20M and was wondering why 10M uploads weren't working...
[/quote]
It could be because of your max execution time.`
28-Oct-2005 08:44
`Note that post_max_size also needs to be considered, by default it is 8M. I raised my upload_max_filesize to 20M and was wondering why 10M uploads weren't working...`
jest3r at mtonic dot net
19-Oct-2005 09:10
`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`
mikelone
06-Sep-2005 08:46
`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) ......`
espiao at gmail dot com
27-Jul-2005 07:25
`/**
* 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);`
Darrell
18-May-2005 02:51
`move_uploaded_file apparently uses the root of the Apache installation (e.g. "Apache Group\Apache2" under Windows) as the upload location if relative pathnames are used.
For example,
$ftmp = $_FILES['userfile']['tmp_name'];
$fname = $_FILES['userfile']['name'];
move_uploaded_file($ftmp, $fname);
moves the file to
"Apache Group\Apache2\$fname";
In contrast, other file/directory related functions use the current directory of the php script as the offset for relative pathnames. So, for example, if the command
mkdir('tmp');
is called from 'Apache Group\Apache2\htdocs\testpages\upload.php', the result is to create
'Apache Group\Apache2\htdocs\testpages\tmp'
On the other hand, if 'mkdir' is called just before 'move_uploaded_file', the behavior changes. The commands,
mkdir('tmp');
move_uploaded_file($ftmp, $fname);
used together result in
"Apache Group\Apache2\htdocs\testpages\tmp\$fname"
being created. Wonder if this is a bug or a feature.
Darrell`
andrew@euperia,com
04-Apr-2005 02:29
`Instead of using chdir or chmod 0777 a safer alternative to move_uploaded_files is to use PHP's ftp functions to move the file into a web dir.
1. Make ftp connection to 127.0.0.1 with the correct username and password.
2. ftp_chdir to the required directory.
3. ftp_put ($_FILES['myfile']['tmp_name'], $finalfilename);
4. ftp quit.`
richardNO at SPAMbesite dot nl
11-Mar-2005 04:32
`Creating the dir with mkdir from php is a security risk too. Everyone who can run a php script on the server can write a script to mess with the dir.`
user at php dot net
01-Mar-2005 02:54
`Giving the directory 777 permission is not a good idea for security reasons, it would be better to create the directory using "mkdir()".
That will make php user (usually "nobody") the owner of the directory, and permissions will not be a problem.`
subway
17-Feb-2005 02:18
`Don't forget to set chmod to 777 for the directory to which you want to move the file.
Otherwise you will maybe get "failed to open stream: Permission denied in ..."!`
Michel S
16-Feb-2005 09:41
`I once had a problem with this function. File was uploaded correctly, but I still had to chmod the file afterwards. It could not be used otherwise.
Michel S`
allan666 at NOSPAM dot gmail dot com
16-Dec-2004 10:35
`On the Fedora Core 3 Linux distribution, you may get a "failed to open stream: Permission denied in ..." message. I fact changing the permission of the directory will not work (even if you set to 0777). It is because of the new SELinux kernel that allow apache user to write only in /tmp dir (I think). In order to solve the problem you must to disable the SELinux (at least for apache service) to allow the server to write in other directories. To do that, run the system-config-securitylevel app and disable the SE to apache service. Reboot your system and continue your work. Hope it helps!`
php at f00n dot com
04-Jul-2004 01:17
`If you are building an intranet framework and use NAT/Routing heed the following advice.
If you want to move uploaded files to an FTP server you cannot use the ftp wrapper (ie. 'ftp://user:pass@ftpserver/') as part of your move_uploaded_file() action. This is due to the wrapper only using passive mode with ftp.
The only workaround is using the ftp functions (may not be compiled by default with *nix but is by default with windows).`
froid_nordik at sympatico dot ca
04-Jun-2004 09:26
`Make sure the directory you are moving the file to exists before using this command.`
sauron at nospam on morannon dot org
08-Mar-2004 05:20
`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.`
mail at johan dot it
28-Feb-2004 02:14
`Warning: If you save a md5_file hash in a database to keep record of uploaded files, which is usefull to prevent users from uploading the same file twice, be aware that after using move_uploaded_file the md5_file hash changes! And you are unable to find the corresponding hash and delete it in the database, when a file is deleted.`
mina86 at tlen dot pl
07-Dec-2003 03:03
`Hey! Why not using strrchr() to get file extension:
<?php $ext = strrchr($_FILES['file']['name'], '.'); ?>
or to get it without '.' at the begining:
<?php $ext = substr(strrchr($_FILES['file']['name'], '.'), 1); ?>
If you want to update file without any strang characters you can use:
<?php
move_uploaded_file(
$_FILES["file"]["tmp_name"],
$dir . preg_replace('/[^a-z0-9_\-\.]/i', '_', $_FILES["file"]["name"])
);
?>`
wolke74 at web dot de
18-Nov-2003 09:02
`French and English filenames --- as it is not forbidden -- often have an apostrophy, for instance "That's advertisement paper.doc" or "Les aventures d'Alice dans le pays du miracle.doc". However, uploading such files can run into trouble.
So you can write, if the posted file had been marked by myfile .
if(!move_uploaded_file($_FILES["myfile"]["tmp_name"],
rawurlencode($mydir.$_FILES["myfile"]["name"]))
{
echo "Something is wrong with the file";
exit;
}`
08-Nov-2003 07:54
`The example to find file extension bellow is quite confusing and its using to much code for a much simpler solution. Which is in example:
$file_parts = pathinfo('dir/' . $_FILES['file']['name']);
$file_extension = strtolower($file_parts['extension']);
The 'dir/' part is only to get a valid path.`
www at w8c dot com
09-Oct-2003 12:03
`function upload($filedir,$source,$source_name,$up_flag,$lastname)
{
if (!file_exists($filedir))
{
mkdir($filedir,0777);
}
@chmod($filedir,0777);
if (!$lastname)
{
$lastname=$source_name;
}
if (file_exists("$filedir/$lastname"))
{
if ($up_flag=="y")
{
@unlink($filedir/$lastname);
@move_uploaded_file($source,"$filedir/$lastname");
echo "$source_name OK<br>";
}
else
echo "$source_name ...<br>";
}
else
{
@move_uploaded_file($source,"$filedir/$lastname");
echo "$source_name OK<br>";
}
}`
allen at brooker dot gb dot net
12-Feb-2003 02:48
`The first comment totally threw me off. Under the 'new regime', the 'string filename' is $_FILES['userfile']['tmp_name']
Also note that the 'string destination' should be the full path and filename. As long as your server isnt using virtual hosting, you should be able to use $_SERVER['DOCUMENT_ROOT'] . "path/within/website". This'll save hours of hassle trying to get sometimes ignorant ISPs to give you your full and 'no symlinks' path.
Allen`
add a note
parse_ini_file mkdir

Last updated: Fri, 26 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST