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

Путь к загруженному файлу.

destination

Назначение перемещаемого файла.

Возвращаемые значения

В случае успеха возвращает TRUE.

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

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

Примеры

Пример #1 Загрузка нескольких файлов

<?php
$uploads_dir 
'/uploads';
foreach (
$_FILES["pictures"]["error"] as $key => $error) {
    if (
$error == UPLOAD_ERR_OK) {
        
$tmp_name $_FILES["pictures"]["tmp_name"][$key];
        
$name $_FILES["pictures"]["name"][$key];
        
move_uploaded_file($tmp_name"$uploads_dir/$name");
    }
}
?>

Примечания

Замечание:

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

Внимание

Если результирующий файл уже существует, он будет перезаписан.

Смотрите также

Коментарии

Автор:
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.
2003-11-08 21:54:28
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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.
2004-02-28 16:14:33
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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.
2004-03-08 07:20:35
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Make sure the directory you are moving the file to exists before using this command.
2004-06-04 12:26:42
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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!
2004-12-17 00:35:40
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
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
2005-02-16 11:41:33
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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.
2005-03-01 04:54:34
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
/**
 * 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);
2005-07-27 10:25:30
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
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) ......
2005-09-06 11:46:31
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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
2005-10-20 00:10:48
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
[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.
2005-11-04 17:56:08
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
Microsoft returns image/pjpeg not image/jpg when using $_FILES['imageName']['type'];
2005-11-07 15:27:04
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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($origen0strlen($origen)-4);
       
$file_extension  substr($origenstrlen($origen)-4strlen($origen));
       
$frand $file_name."[$i]".$file_extension;
       
$destinoFull $destinoDir.$frand;
       
$i++;
    }
   
    if (
move_uploaded_file($ftemporal$destinoFull))    return $frand;
    else                                                 return 
"0";
}
?>
2005-12-14 07:30:25
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
---------
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
2005-12-16 00:28:12
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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!
2006-01-09 23:31:48
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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";
}
2006-01-31 13:10:06
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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.
2006-02-03 00:35:52
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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
2006-02-16 02:26:35
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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>";
?>
2006-04-05 12:29:54
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
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=1file_exists($fulldest); $i++)
  {
   
$fileext = (strpos($origin,'.')===false?'':'.'.substr(strrchr($origin"."), 1));
   
$filename substr($origin0strlen($origin)-strlen($fileext)).'['.$i.']'.$fileext;
   
$fulldest $dest.$newfilename;
  }
 
  if (
move_uploaded_file($tmp_name$fulldest))
    return 
$filename;
  return 
false;
}
?>
2006-04-13 21:12:07
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
small typo:

$fulldest = $dest.$newfilename;

show be

$fulldest = $dest.$filename;

or you would have infinite loop.
2006-04-20 17:04:23
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
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.
2006-08-22 21:18:49
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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. 

function.rename

(move_uploaded_file() won't work, since the POST vars won't be present.)
2006-09-10 03:28:21
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
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.
2007-02-03 09:32:54
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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!
2007-03-06 07:07:48
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
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));
2007-03-06 23:38:51
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
I could be wrong, but I usualy use 

$uploadext = strtolower(strrchr($imagename,"."));

to find the file extension when uploading, as opposed to explode().
2007-03-22 09:47:38
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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
2007-04-19 11:45:51
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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:

<IfModule mod_php4.c>
php_value upload_max_filesize 50M
php_value post_max_size 50M
</IfModule>

- means 50MB upload limit.
2007-05-04 14:02:31
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
I found a great resource concerning uploads with PHP:

http://www.radinks.com/upload/config.php

They explain and tell how to optimize PHP installation to handle large file uploads. Helped me a lot!
2007-05-30 11:49:21
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
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.
2007-06-10 16:58:18
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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.
2007-07-16 14:29:55
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
when you get this 2 Warnings - paths are a real sample - ::

-
move_uploaded_file(/uploads/images/sample.png) [function.move-uploaded-file]: failed to open stream: No such file or directory in /scripts/php/system/upload-file.php on line X
-

and

-
move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/somefilename' to '/uploads/images/sample.png' in /scripts/php/system/upload-file.php on line X
-

probably the path '/uploads/images/sample.png' is incomplete, in my case the complet path is "/home/x-user/public_html/uploads/images/sample.png"

you can use getcwd() to know the current working directory.

:)
2007-09-07 05:38:48
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
I was getting error code 1 (features.file-upload.errors), indicating that the file exceeded upload_max_filesize. To fix this, run <?php ini_set("upload_max_filesize""100M"); ?> (then restart apache) changing the second argument to your limit.
2008-03-26 09:41:14
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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!
2008-08-17 17:02:01
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
<?php 

if(isset($_FILES['uploaded'])){
$target "galleries/".basename($_FILES['uploaded']['name']) ;
print_r($_FILES);

if(
move_uploaded_file($_FILES['uploaded']['tmp_name'],$target)) echo "OK!";//$chmod o+rw galleries

}
else{
 echo 
"<form enctype='multipart/form-data' action='CodeTool.php' method='POST'>";
 echo 
"File:<input name='uploaded' type='file'/><input type='submit' value='Upload'/>";
 echo 
"</form>";
}

?>
2008-08-23 15:22:21
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
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.
2008-08-27 12:36:13
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
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.
2008-10-13 16:41:19
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
I had exactly than" tnp at shaman dot co dot uk" : move_uploaded_file() is either asynchronous or uses some kind of virtual filesystem. But you may encounter big problems when trying to access a file just uploaded, especially is you tried to change the name.
If you have problems where the uploaded file seems unaccessible, try to use copy() instead.
2008-11-24 14:44:04
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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.

<?php
//  5MB maximum file size
$MAXIMUM_FILESIZE 1024 1024;
//  Valid file extensions (images, word, excel, powerpoint)
$rEFileTypes 
 
"/^\.(jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|
        ppt|pptx){1}$/i"
;
$dir_base "/your/file/location/";

$isFile is_uploaded_file($_FILES['Filedata']['tmp_name']);
if (
$isFile)    //  do we have a file?
   
{//  sanatize file name
    //     - remove extra spaces/convert to _, 
    //     - remove non 0-9a-Z._- characters,
    //     - remove leading/trailing spaces
    //  check if under 5MB, 
    //  check file extension for legal file types
   
$safe_filename preg_replace(
                     array(
"/\s+/""/[^-\.\w]+/"), 
                     array(
"_"""), 
                     
trim($_FILES['Filedata']['name']));
    if (
$_FILES['Filedata']['size'] <= $MAXIMUM_FILESIZE && 
       
preg_match($rEFileTypesstrrchr($safe_filename'.')))
      {
$isMove move_uploaded_file (
                 
$_FILES['Filedata']['tmp_name'], 
                 
$dir_base.$safe_filename);}
      }
   } 
?>

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.)
2009-10-18 03:21:42
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
When you use move_uploaded_file function to upload a file with utf-8  filename to linux system, you probably check your result by browsing to see the file in the target directory so please make sure that your terminal emulator or your samba configuration is set the character encoding to utf-8 otherwise  your file will be shown as ?????? (unreadable character).
2009-10-19 03:03:32
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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

<?php
function uploadFiles() {
   
$num_args func_num_args();
   
$arg_list func_get_args();
   
   
$valReturn false;
   
$i 0;
   
$unlinkElement = array();
    foreach(
$arg_list as $key=>$value) {
        if(
is_array($value) AND is_array($value[0])) {
            if(
$value[0]['error'] == AND isset($value[1])) {
                if(
$value[0]['size'] > AND $value[0]['size'] < 500000) {
                   
$typeAccepted = array("image/jpeg""image/gif""image/png");
                    if(
in_array($value[0]['type'],$typeAccepted)) {   
                       
$destination $value[1];
                        if(isset(
$value[2])) {
                           
$extension substr($value[0]['name'] , strrpos($value[0]['name'] , '.') +1);
                           
$destination .= (str_replace(" ","-",$value[2])).".".$extension;
                        } else {
                           
$destination .= $value[0]['name'];
                        }
                       
                        if(
move_uploaded_file($value[0]['tmp_name'],$destination)) {
                           
$i++;
                           
$unlinkElement[] = $destination;
                        }
                    }
                }
            }
        }
    }
    if(
$i == $num_args) {
       
$valReturn true;
    } else {
        foreach(
$unlinkElement as $value) {
           
unlink($value);
        }
    }
    return 
$valReturn;
}
?>

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"));

<?php

$file_one 
= array($_FILES['file_one'],$destination,$name_one);
$file_two = array($_FILES['file_two'],$destination); //The name will be the same that $_FILES[]['name']

if(uploadFiles($file_one,$file_two)) {
    echo 
"true";
} else {
    echo 
"false";
}
?>
2009-11-13 06:50:45
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
I have for a couple of years been stymed to understand how to effectively load images (of more than 2MB) and then create thumbnails.  My note below on general file uploading was an early hint of some of the system default limitations and I have recently discovered the final limit  I offer this as an example of the various missing pieces of information to successfully load images of more than 2MB and then create thumbnails.  This particular example assumes a picture of a user is being uploaded and because of browser caching needs a unique number at the end to make the browser load a new picture for review at the time of upload.  The overall calling program I am using is a Flex based application which calls this php file to upload user thumbnails.

The secret sauce is:

1.  adjust server memory size, file upload size, and post size
2.  convert image to standard formate (in this case jpg) and scale

The server may be adjusted with the .htaccess file or inline code.  This example has an .htaccess file with file upload size and post size and then inline code for dynamic system memory.

htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M

<?php 
//  $img_base = base directory structure for thumbnail images
//  $w_dst = maximum width of thumbnail
//  $h_dst = maximum height of thumbnail
//  $n_img = new thumbnail name
//  $o_img = old thumbnail name
function convertPic($img_base$w_dst$h_dst$n_img$o_img)
  {
ini_set('memory_limit''100M');   //  handle large images
   
unlink($img_base.$n_img);         //  remove old images if present
   
unlink($img_base.$o_img);
   
$new_img $img_base.$n_img;
     
   
$file_src $img_base."img.jpg"//  temporary safe image storage
   
unlink($file_src);
   
move_uploaded_file($_FILES['Filedata']['tmp_name'], $file_src);
             
   list(
$w_src$h_src$type) = getimagesize($file_src);     // create new dimensions, keeping aspect ratio
   
$ratio $w_src/$h_src;
   if (
$w_dst/$h_dst $ratio) {$w_dst floor($h_dst*$ratio);} else {$h_dst floor($w_dst/$ratio);}

   switch (
$type)
     {case 
1:   //   gif -> jpg
       
$img_src imagecreatefromgif($file_src);
        break;
      case 
2:   //   jpeg -> jpg
       
$img_src imagecreatefromjpeg($file_src); 
        break;
      case 
3//   png -> jpg
       
$img_src imagecreatefrompng($file_src);
        break;
     }
   
$img_dst imagecreatetruecolor($w_dst$h_dst);  //  resample
   
   
imagecopyresampled($img_dst$img_src0000$w_dst$h_dst$w_src$h_src);
   
imagejpeg($img_dst$new_img);    //  save new image

   
unlink($file_src);  //  clean up image storage
   
imagedestroy($img_src);       
   
imagedestroy($img_dst);
  }

$p_id = (Integer) $_POST[uid];
$ver = (Integer) $_POST[ver];
$delver = (Integer) $_POST[delver];
convertPic("your/file/structure/"150150"u".$p_id."v".$ver.".jpg""u".$p_id."v".$delver.".jpg");

?>
2010-02-15 13:34:33
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
You can only move the uploaded file once.  You can use copy() if you need the file in more than one place.
<?php // RAY_temp_upload_example.php
error_reporting(E_ALL);
echo 
"<pre>" PHP_EOL;

// IF A FILE HAS BEEN UPLOADED
if (!empty($_FILES))
{
   
// SHOW THE UPLOADED FILES
   
print_r($_FILES);

   
// TRY TO MOVE THE FILE TWICE - SECOND MOVE RETURNS FALSE
   
if (!move_uploaded_file($_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["name"])) echo "CANNOT MOVE {$_FILES["userfile"]["name"]}" PHP_EOL;
    if (!
move_uploaded_file($_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["name"])) echo "CANNOT MOVE {$_FILES["userfile"]["name"]}" PHP_EOL;

   
// SHOW THE UPLOADED FILES AFTER THE MOVE - NO VISIBLE CHANGE
   
print_r($_FILES);
}

// END OF PHP, PUT UP THE HTML FORM TO GET THE FILE
?>
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>
2010-08-18 11:42:50
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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.
2011-03-30 15:55:42
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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_).
2011-05-03 19:07:52
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
The destination directory must exist; move_uploaded_file() will not automatically create it for you.
2011-07-22 16:26:58
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
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.
2012-03-31 07:41:21
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
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

<?php

/**
 * Check $_FILES[][name]
 *
 * @param (string) $filename - Uploaded file name.
 * @author Yousef Ismaeil Cliprz
 */
function check_file_uploaded_name ($filename)
{
    (bool) ((
preg_match("`^[-0-9A-Z_\.]+$`i",$filename)) ? true false);
}

?>

Third : make sure that the file name not bigger than 250 characters.

as in example :

<?php

/**
 * Check $_FILES[][name] length.
 *
 * @param (string) $filename - Uploaded file name.
 * @author Yousef Ismaeil Cliprz.
 */
function check_file_uploaded_length ($filename)
{
    return (bool) ((
mb_strlen($filename,"UTF-8") > 225) ? true false);
}

?>

Fourth: Check File extensions and Mime Types that you want to allow in your project. You can use : pathinfo() http://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

<?php

$ext_type 
= array('gif','jpg','jpe','jpeg','png');

?>

You have multi choices to checking extensions and Mime types.

Fifth: Check file size and make sure the limit of php.ini to upload files is what you want, You can start from ini.core#ini.file-uploads

And last but not least : Check the file content if have a bad codes or something like this function function.file-get-contents.

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
Options -ExecCGI 

Do not forget this steps for your project protection.
2013-02-18 00:59:42
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
Re: Florian S. in H. an der E. [.de]'s point about directory stick bits, I got hit by this a bunch since I use groups and dir sticky bits to secure my site, so I wrote this replacement, which others might find useful:

/**
 * obey sticky bit with move_uploaded_file
 *
 */
function wp_move_uploaded_file( $filename, $destination ) {
  define("STICKYGRPDIR",042010);
  $stat = stat(dirname($destination));
  if(move_uploaded_file($filename,$destination)) {
    if($stat['mode'] & STICKYGRPDIR) {
      return chgrp($destination,$stat['gid']);
    }
  } else {
    return false;
  }
}
2014-05-09 09:26:40
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
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:

   if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file)) {
      echo "<P>FILE UPLOADED TO: $target_file</P>";
   } else {
      echo "<P>MOVE UPLOADED FILE FAILED!</P>";
      print_r(error_get_last());
   }
2015-01-05 17:33:21
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
Автор:
Also be aware that ini_get('post_max_size') doesn't return a numeric value; it literally returns the string '16M' or similar.
2017-06-13 00:39:14
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
this is what i use to colect data for multiple uploads
$form_field - html form field name
function upl_img_data_multy($form_field){

   $files_data = array();
   $submited_files = $_FILES[$form_field];
   $submited_files_tmp_name = $submited_files["tmp_name"];

    foreach($submited_files_tmp_name as $key => $tmp_name){
        $files_data[$key] = array();
        $size_data =  getimagesize($tmp_name);
        $files_data[$key]["name"] = basename($submited_files["name"][$key]);
        $files_data[$key]["tmp_name"] = $_FILES[$form_field]["tmp_name"][$key];
        $files_data[$key]["type"] = $_FILES[$form_field]["type"][$key];   
        $files_data[$key]["size-w"] = $size_data[0];
        $files_data[$key]["size-h"] = $size_data[1];
        $files_data[$key]["size"] = $_FILES[$form_field]["size"][$key];
        $files_data[$key]["error"] = $_FILES[$form_field]["error"][$key];   
    }
   
   return $files_data;
}
2017-12-15 21:26:03
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html
<?php 
   
class UploadTool {
       
/**
        * @var arr => $upload_info = infos sobre os arquivos enviados
        */
       
private $upload_info = array();
       
/**
        * @param str => $input_name = nome do input
        * @param str => $folder_to_move = nome da pasta em que o arquivo será salvo
        * @param arr => $mime_allowed = mime types permitidos no processo de upload
        * @param bol => $return_json = se true retorna um objeto json
        */
       
public function manage_single_file(string $input_namestring $folder_to_move, array $mime_allowed = [], bool $return_json true){
           
$resultado = array();
           
$count_mime_allowed count($mime_allowed);
            if(
is_uploaded_file($_FILES[$input_name]['tmp_name'])){
               
$new_name_file bin2hex(random_bytes(64)).'.'.pathinfo($_FILES[$input_name]['name'], PATHINFO_EXTENSION);
               
$this->upload_info = array(
                   
'name' => $new_name_file,
                   
'size' => $_FILES[$input_name]['size'],
                   
'mime' => finfo_file(finfo_open(FILEINFO_MIME_TYPE), $_FILES[$input_name]['tmp_name']),
                   
'extension' => pathinfo($_FILES[$input_name]['name'], PATHINFO_EXTENSION),
                   
'check_mime' => true,
                   
'folder_to_move' => $folder_to_move,
                   
'error_code' => $_FILES[$input_name]['error'],
                );
                if(
$count_mime_allowed && !in_array($this->upload_info['mime'], $mime_allowedtrue)){$this->upload_info['check_mime'] = false;}
                if(
$this->upload_info['error_code'] === && $this->upload_info['check_mime'] === true){move_uploaded_file($_FILES[$input_name]['tmp_name'], $folder_to_move.$this->upload_info['name']);}
            }
           
$resultado['upload_info'] = $this->upload_info;
            if(
$return_json){echo json_encode($resultado);}
            if(!
$return_json){return $resultado;}
        }
       
/**
        * @param str => $input_name = nome do input
        * @param str => $folder_to_move = nome da pasta em que o arquivo será salvo
        * @param arr => $mime_allowed = mime types permitidos no processo de upload
        * @param bol => $return_json = se true retorna um objeto json
        */
       
public function manage_multiple_file(string $input_namestring $folder_to_move, array $mime_allowed = [], bool $return_json true){
           
$resultado = array();
           
$count_mime_allowed count($mime_allowed);
           
$qtd_arquivos_enviados count($_FILES[$input_name]['tmp_name']);
            for(
$i 0$i $qtd_arquivos_enviados$i++){
                if(
is_uploaded_file($_FILES[$input_name]['tmp_name'][$i])){
                   
$new_name_file bin2hex(random_bytes(64)).'.'.pathinfo($_FILES[$input_name]['name'][$i], PATHINFO_EXTENSION);
                   
$this->upload_info[] = array(
                       
'name' => $new_name_file,
                       
'size' => $_FILES[$input_name]['size'][$i],
                       
'mime' => finfo_file(finfo_open(FILEINFO_MIME_TYPE), $_FILES[$input_name]['tmp_name'][$i]),
                       
'extension' => pathinfo($_FILES[$input_name]['name'][$i], PATHINFO_EXTENSION),
                       
'check_mime' => true,
                       
'folder_to_move' => $folder_to_move,
                       
'error_code' => $_FILES[$input_name]['error'][$i],
                    );
                    if(
$count_mime_allowed && !in_array($this->upload_info[$i]['mime'], $mime_allowedtrue)){$this->upload_info[$i]['check_mime'] = false;}
                    if(
$this->upload_info[$i]['error_code'] === && $this->upload_info[$i]['check_mime'] === true){move_uploaded_file($_FILES[$input_name]['tmp_name'][$i], $folder_to_move.$this->upload_info[$i]['name']);}
                }
            }
           
$resultado['upload_info'] = $this->upload_info;
            if(
$return_json){echo json_encode($resultado);}
            if(!
$return_json){return $resultado;}
        }
    }
    if(
$_FILES){(new UploadTool)->manage_multiple_file('input_arquivos'__DIR__.'/pasta/');}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'?>" enctype="multipart/form-data">
    <input type="file" name="input_arquivos[]" multiple="true">
    <button type="submit">enviar</button>
</form>
2018-06-15 03:44:54
http://php5.kiev.ua/manual/ru/function.move-uploaded-file.html

    Поддержать сайт на родительском проекте КГБ