文件上传处理
在线手册:中文 英文
PHP手册

POST 方法上传

本特性可以使用户上传文本和二进制文件。用 PHP 的认证和文件操作函数,可以完全控制允许哪些人上传以及文件上传后怎样处理。

PHP 能够接受任何来自符合 RFC-1867 标准的浏览器(包括 Netscape Navigator 3 及更高版本,打了补丁的 Microsoft Internet Explorer 3 或者更高版本)上传的文件。

Note: 相关的设置

请参阅 php.inifile_uploadsupload_max_filesizeupload_tmp_dirpost_max_size 以及 max_input_time 设置选项。

请注意 PHP 也支持 PUT 方法的文件上传,Netscape Composer 和 W3C 的 Amaya 客户端使用这种方法。请参阅对 PUT 方法的支持以获取更多信息。

Example #1 文件上传表单

可以如下建立一个特殊的表单来支持文件上传:

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

以上范例中的 __URL__ 应该被换掉,指向一个真实的 PHP 文件。

MAX_FILE_SIZE 隐藏字段(单位为字节)必须放在文件输入字段之前,其值为接收文件的最大尺寸。这是对浏览器的一个建议,PHP 也会检查此项。在浏览器端可以简单绕过此设置,因此不要指望用此特性来阻挡大文件。实际上,PHP 设置中的上传文件最大值是不会失效的。但是最好还是在表单中加上此项目,因为它可以避免用户在花时间等待上传大文件之后才发现文件过大上传失败的麻烦。

Note:

要确保文件上传表单的属性是 enctype="multipart/form-data",否则文件上传不了。

全局变量 $_FILES 自 PHP 4.1.0 起存在(在更早的版本中用 $HTTP_POST_FILES 替代)。此数组包含有所有上传的文件信息。

以上范例中 $_FILES 数组的内容如下所示。我们假设文件上传字段的名称如上例所示,为 userfile。名称可随意命名。

$_FILES['userfile']['name']

客户端机器文件的原名称。

$_FILES['userfile']['type']

文件的 MIME 类型,如果浏览器提供此信息的话。一个例子是“image/gif”。不过此 MIME 类型在 PHP 端并不检查,因此不要想当然认为有这个值。

$_FILES['userfile']['size']

已上传文件的大小,单位为字节。

$_FILES['userfile']['tmp_name']

文件被上传后在服务端储存的临时文件名。

$_FILES['userfile']['error']

和该文件上传相关的错误代码。此项目是在 PHP 4.2.0 版本中增加的。

文件被上传后,默认地会被储存到服务端的默认临时目录中,除非 php.ini 中的 upload_tmp_dir 设置为其它的路径。服务端的默认临时目录可以通过更改 PHP 运行环境的环境变量 TMPDIR 来重新设置,但是在 PHP 脚本内部通过运行 putenv() 函数来设置是不起作用的。该环境变量也可以用来确认其它的操作也是在上传的文件上进行的。

Example #2 使文件上传生效

请查阅函数 is_uploaded_file()move_uploaded_file() 以获取进一步的信息。以下范例处理由表单提供的文件上传。

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir '/var/www/uploads/';
$uploadfile $uploaddir basename($_FILES['userfile']['name']);

echo 
'<pre>';
if (
move_uploaded_file($_FILES['userfile']['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>";

?>

接受上传文件的 PHP 脚本为了决定接下来要对该文件进行哪些操作,应该实现任何逻辑上必要的检查。例如可以用 $_FILES['userfile']['size'] 变量来排除过大或过小的文件,也可以通过 $_FILES['userfile']['type'] 变量来排除文件类型和某种标准不相符合的文件,但只把这个当作一系列检查中的第一步,因为此值完全由客户端控制而在 PHP 端并不检查。自 PHP 4.2.0 起,还可以通过 $_FILES['userfile']['error'] 变量来根据不同的错误代码来计划下一步如何处理。不管怎样,要么将该文件从临时目录中删除,要么将其移动到其它的地方。

如果表单中没有选择上传的文件,则 PHP 变量 $_FILES['userfile']['size'] 的值将为 0,$_FILES['userfile']['tmp_name'] 将为空。

如果该文件没有被移动到其它地方也没有被改名,则该文件将在表单请求结束时被删除。

Example #3 上传一组文件

PHP 的 HTML 数组特性甚至支持文件类型。

<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
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"data/$name");
    }
}
?>

文件上传处理
在线手册:中文 英文
PHP手册
PHP手册 - N: POST 方法上传

用户评论:

gustavo at roskus dot com (08-Aug-2011 08:21)

Some hosting does not have permission to use the move_uploaded_file function should replace the copy function

Age Bosma (10-Jun-2011 10:49)

"If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none."

Note that the situation above is the same when a file exceeding the MAX_FILE_SIZE hidden field is being uploaded. In this case $_FILES['userfile']['size'] is also set to 0, and $_FILES['userfile']['tmp_name'] is also empty. The difference would only be the error code.
Simply checking for these two conditions and assuming no file upload has been attempted is incorrect.

Instead, check if $_FILES['userfile']['name'] is set or not. If it is, a file upload has at least been attempted (a failed attempt or not). If it is not set, no attempt has been made.

zingaburga at hotmail dot com (03-Feb-2011 03:09)

The documentation is a little unclear about the MAX_FILE_SIZE value sent in the form with multiple file input fields.  The following is what I have found through testing - hopefully it may clarify it for others.

The MAX_FILE_SIZE is applied to each file (not the total size of all files) and to all file inputs which appear after it.  This means that it can be overridden for different file fields.  You can also disable it by sending no number, or sending 0 (probably anything that == '0' if you think about it).

Example:

<form enctype="multipart/form-data" action="." method="POST">
  <!-- no maximum size for userfile0 -->
  <input name="userfile0" type="file" />

  <input type="hidden" name="MAX_FILE_SIZE" value="1000" />
  <!-- maximum size for userfile1 is 1000 bytes -->
  <input name="userfile1" type="file" />
  <!-- maximum size for userfile2 is 1000 bytes -->
  <input name="userfile2" type="file" />

  <input type="hidden" name="MAX_FILE_SIZE" value="2000" />
  <!-- maximum size for userfile3 is 2000 bytes -->
  <input name="userfile3" type="file" />

  <input type="hidden" name="MAX_FILE_SIZE" value="0" />
  <!-- no maximum size for userfile4 -->
  <input name="userfile4" type="file" />
</form>

mail at markuszeller dot com (10-Jan-2011 08:34)

If you want to increase the upload size, it could make sense to allow it only to a specified directory and not in the php.ini for the whole domain or server. In my case it worked very well placing that into the .htaccess file like this:

php_value    upload_max_filesize    100M
php_value    post_max_size    101M

Remember, post_max_size must be bigger than the upload_max_filesize.

Mark (30-Sep-2010 12:12)

$_FILES will be empty if a user attempts to upload a file greater than post_max_size in your php.ini

post_max_size should be >= upload_max_filesize in your php.ini.

michael (05-Dec-2009 05:19)

Just a little note, when I was trying to get this to work on my webserver I got error telling me the permissions were wrong, I checked and couldn't see anything wrong then I thought to try "./" for my upload directory instead of the full address which was something like "home/username/public_html/uploaddir". This will save it in the same directory as your script for the program above thats something like

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = './';//<----This is all I changed
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo
'<pre>';
if (
move_uploaded_file($_FILES['userfile']['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>";

?>

I know something trivial but when your new to this, those kind of things elude you.

daevid at daevid dot com (11-Jun-2009 10:35)

I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:

Array
(
    [0] => Array
        (
            [name] => facepalm.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpn3FmFr
            [error] => 0
            [size] => 15476
        )

    [1] => Array
        (
            [name] =>
            [type] =>
            [tmp_name] =>
            [error] => 4
            [size] =>
        )
)

and not this
Array
(
    [name] => Array
        (
            [0] => facepalm.jpg
            [1] =>
        )

    [type] => Array
        (
            [0] => image/jpeg
            [1] =>
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpn3FmFr
            [1] =>
        )

    [error] => Array
        (
            [0] => 0
            [1] => 4
        )

    [size] => Array
        (
            [0] => 15476
            [1] => 0
        )
)

Anyways, here is a fuller example than the sparce one in the documentation above:

<?php
foreach ($_FILES["attachment"]["error"] as $key => $error)
{
      
$tmp_name = $_FILES["attachment"]["tmp_name"][$key];
       if (!
$tmp_name) continue;

      
$name = basename($_FILES["attachment"]["name"][$key]);

    if (
$error == UPLOAD_ERR_OK)
    {
        if (
move_uploaded_file($tmp_name, "/tmp/".$name) )
           
$uploaded_array[] .= "Uploaded file '".$name."'.<br/>\n";
        else
           
$errormsg .= "Could not move uploaded file '".$tmp_name."' to '".$name."'<br/>\n";
    }
    else
$errormsg .= "Upload error. [".$error."] on file '".$name."'<br/>\n";
}
?>

eslindsey at gmail dot com (30-Mar-2009 07:09)

Also note that since MAX_FILE_SIZE hidden field is supplied by the browser doing the submitting, it is easily overridden from the clients' side.  You should always perform your own examination and error checking of the file after it reaches you, instead of relying on information submitted by the client.  This includes checks for file size (always check the length of the actual data versus the reported file size) as well as file type (the MIME type submitted by the browser can be inaccurate at best, and intentionally set to an incorrect value at worst).

claude dot pache at gmail dot com (19-Mar-2009 05:26)

Note that the MAX_FILE_SIZE hidden field is only used by the PHP script which receives the request, as an instruction to reject files larger than the given bound. This field has no significance for the browser, it does not provide a client-side check of the file-size, and it has nothing to do with web standards or browser features.