Chinaunix首页 | 论坛 | 博客
  • 博客访问: 411625
  • 博文数量: 95
  • 博客积分: 5001
  • 博客等级: 大校
  • 技术积分: 1030
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-13 11:43
文章分类

全部博文(95)

文章存档

2007年(95)

我的朋友

分类:

2007-05-26 00:43:20

(PHP 4 >= 4.0.3, PHP 5)

move_uploaded_file -- 将上传的文件移动到新位置

说明

bool move_uploaded_file ( string filename, string destination )

本函数检查并确保由 filename 指定的文件是合法的上传文件(即通过 PHP 的 HTTP POST 上传机制所上传的)。如果文件合法,则将其移动为由 destination 指定的文件。

如果 filename 不是合法的上传文件,不会出现任何操作,move_uploaded_file() 将返回 FALSE

如果 filename 是合法的上传文件,但出于某些原因无法移动,不会出现任何操作,move_uploaded_file() 将返回 FALSE。此外还会发出一条警告。

这种检查显得格外重要,如果上传的文件有可能会造成对用户或本系统的其他用户显示其内容的话。

注: move_uploaded_file() 对和 都是敏感的。不过,限制只针对 destination 路径,因为允许移动上传的文件名 filename 可能会与这些限制产生冲突。move_uploaded_file() 仅作用于通过 PHP 上传的文件以确保这个操作的安全性。

警告

如果目标文件已经存在,将会被覆盖。

参见 ,以及一章中的简单使用例子。


User Contributed Notes
Nibinaear
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!

  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
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.



(move_uploaded_file() won't work, since the POST vars won't be present.)
Rob Szarka
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
small typo:

$fulldest = $dest.$newfilename;

show be

$fulldest = $dest.$filename;

or you would have infinite loop.
Zarel
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).

// 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
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.

$uploaddir = '';
$uploadfile = $uploaddir . basename($_FILES['upfile']['name']);
echo
'
';
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
"
"
;
?>
ffproberen2 at dodgeit dot com
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:

 
   Options None
   AllowOverride None
   Order allow,deny
   Allow from all
 


restarted Apache, and the upload succeeded.
j dot m dot thomas at NOSPAM dot blueyonder dot co dot uk
To retrieve the file extension, and various other information about the path, it is easiest to use the pathinfo function.

$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

adam at darkhousemedia dot com
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
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
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
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 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)
---------
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
Great!! my first note here...

This function upload a file.
If file exist, create a copy as "filename[n].ext"

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
Microsoft returns image/pjpeg not image/jpg when using $_FILES['imageName']['type'];
albert
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.
[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.
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
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
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
/**
 * 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
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
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
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
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
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
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
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
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. ') 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
Make sure the directory you are moving the file to exists before using this command.
sauron at nospam on morannon dot org
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
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
Hey! Why not using strrchr() to get file  extension:
= strrchr($_FILES['file']['name'], '.'); ?>
or to get it without '.' at the begining:
= substr(strrchr($_FILES['file']['name'], '.'), 1); ?>

If you want to update file without any strang characters you can use:
move_uploaded_file(
 
$_FILES["file"]["tmp_name"],
 
$dir . preg_replace('/[^a-z0-9_\-\.]/i', '_', $_FILES["file"]["name"])
);
?>
wolke74 at web dot de
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;
}
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
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
";
       }
       else
       echo "$source_name ...
";
   }
   else
   {
       @move_uploaded_file($source,"$filedir/$lastname");
       echo "$source_name OK
";
   }
}
allen at brooker dot gb dot net
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
阅读(53064) | 评论(0) | 转发(0) |
0

上一篇:mysql解决不显示中文?

下一篇:file_exists

给主人留下些什么吧!~~