PHP 文件上传

PHP 的不同版本支持不同的自动全局变量:

自动全局变量 PHP 版本
$_FILES 4.1.0
$HTTP_POST_FILES 4.0.0

变量结构

表达式 内容
$_FILES['userfile']['name'] 客户端文件名
$_FILES['userfile']['type'] 文件类型
$_FILES['userfile']['size'] 文件大小
$_FILES['userfile']['tmp_name'] 服务端文件名
$_FILES['userfile']['error'] 错误代码

错误代码

函数 内容
UPLOAD_ERR_OK = 0 没有错误发生,文件上传成功
UPLOAD_ERR_INI_SIZE = 1 上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值
UPLOAD_ERR_FORM_SIZE = 2 上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值
UPLOAD_ERR_PARTIAL = 3 文件只有部分被上传
UPLOAD_ERR_NO_FILE = 4 没有文件被上传

函数

如不调用此函数,上传的文件将自动删除。

函数 内容
bool move_uploaded_file(oldname, newname) 移动或改名上传的文件,返回是否成功

表单示例:

<form enctype="multipart/form-data" action="_URL_" method="post">

      <input type="hidden" name="MAX_FILE_SIZE" value="30000">
      Send this file: <input name="userfile" type="file">
      <input type="submit" value="Send File">

</form>

PHP 处理代码示例:

<?PHP
    echo $_FILES['userfile']['name'] ."<br>" ;
    echo $_FILES['userfile']['type'] ."<br>" ;
    echo $_FILES['userfile']['size'] ."<br>" ;
    echo $_FILES['userfile']['tmp_name'] ."<br>" ;
    echo $_FILES['userfile']['error'];

    $ff= $_FILES['userfile']['tmp_name'];
    move_uploaded_file($ff,"d:\\temp\\".$_FILES['userfile']['name']);
    echo " 完成";
?>