 |
move_uploaded_file (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() 对安全模式和
open_basedir 都是敏感的。不过,限制只针对
destination 路径,因为允许移动上传的文件名
filename
可能会与这些限制产生冲突。move_uploaded_file()
仅作用于通过 PHP 上传的文件以确保这个操作的安全性。
参见 is_uploaded_file(),以及文件上传处理一章中的简单使用例子。
sergeygrinev at mail dot ru
21-Apr-2006 05:04
small typo:
$fulldest = $dest.$newfilename;
show be
$fulldest = $dest.$filename;
or you would have infinite loop.
Zarel
14-Apr-2006 09: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
06-Apr-2006 12: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 06: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 04: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
03-Feb-2006 02: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
03-Feb-2006 04: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
01-Feb-2006 03: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
10-Jan-2006 01: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)
16-Dec-2005 02: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 09: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
08-Nov-2005 05:27
Microsoft returns image/pjpeg not image/jpg when using $_FILES['imageName']['type'];
albert
08-Nov-2005 04: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.
05-Nov-2005 07: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.
29-Oct-2005 11: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
20-Oct-2005 12: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 11: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 10: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
19-May-2005 05: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
05-Apr-2005 05: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 08: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 06: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 06: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
17-Feb-2005 01: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
17-Dec-2004 02: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 04: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
05-Jun-2004 12: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 09: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
29-Feb-2004 06: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
08-Dec-2003 07: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
19-Nov-2003 01: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;
}
09-Nov-2003 11: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 03: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 06: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
|  |