PHP一步步完结公文上传及上传文件类,php文件上
分类:计算机网络

上传操作代码

一,比较简单的实现文件上传

 代码如下

文件上传原理

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ";
<html xmlns="" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title></title>
</head>
<body>
 
<?php
    if($_FILES['myfile']['error'] > 0) {      //判断文件是否可以成功上传到服务器,0表示上传成功
        echo 'Error: ';
 
        switch ( $_FILES['myfile']['error']  ) {
            case UPLOAD_ERR_OK:
                $response = 'There is no error, the file uploaded with success.';
                break;
            case UPLOAD_ERR_INI_SIZE:
                $response = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $response = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
                break;
            case UPLOAD_ERR_PARTIAL:
                $response = 'The uploaded file was only partially uploaded.';
                break;
            case UPLOAD_ERR_NO_FILE:
                $response = 'No file was uploaded.';
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $response = 'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.';
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $response = 'Failed to write file to disk. Introduced in PHP 5.1.0.';
                break;
            case UPLOAD_ERR_EXTENSION:
                $response = 'File upload stopped by extension. Introduced in PHP 5.2.0.';
                break;
            default:
                $response = 'Unknown error';
                break;
        }
        echo $response;
         
         
        exit;       //如果$_FILES['myfile']['error']大于0都是有错误,输出错误信息并退出程序
    }
     
     //获取上传文件的MIME类型中的主类型和子类型
    list($maintype,$subtype)=explode("/",$_FILES['myfile']['type']);    
     
    if ($maintype=="text") {    //通过主类型限制不能上传文本文件,例如.txt .html .php等文件文件
     
        echo '问题: 不能上传文本文件。';
        exit;                //如果用户上传文本文件则退出程序
         
    }
 
    $upfile = './uploads/'.time().$_FILES['myfile']['name'];     //定义上传后的位置和新文件名
     
    if ( is_uploaded_file($_FILES['myfile']['tmp_name']) ) {     //判断是否为上传文件
     
        if ( !move_uploaded_file($_FILES['myfile']['tmp_name'], $upfile) ) {   //从移动文件
            echo '问题: 不能将文件移动到指定目录。';
            exit;
        }
         
    }else{
         
        echo '问题: 上传文件不是一个合法文件: ';
        echo $_FILES['myfile']['name'];
        exit;
         
    }
 
    echo '文件 :  '.$upfile.'  上传成功, 大小为 : ' .$_FILES['myfile']['size'].'!<br>';   //如果文件上传成功则输出
?>
</body>
</html>

文件上传原理:将客户端的文件先上传到服务器端,然后再将服务器端的临时文件移动到指定的目录。

html

客户端配置

 代码如下

要上传文件,我们需要采用表单,并且表单发送的形式来POST请求,而且要求将enctype设置为multipart/form-data,总结上传的条件如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      ";
<html xmlns="" xml:lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
  <title></title>
</head>
<body>
  <form action="upload.php"  method="post" enctype="multipart/form-data">
          <input type="hidden" name="MAX_FILE_SIZE" value="1000000">
          选择文件:<input type="file" name="myfile">
          <input type="submit" value="上传文件">
      </form>
</body>
</html>

浏览器表单页面

一些常见的上传文件时错误代码

表单发送方式为post
指定enctype=multipart/form-data
客户端的代码:

0 | UPLOAD_ERR_OK         | 文件成功上传
1 | UPLOAD_ERR_INI_SIZE   | Size exceeds upload_max_filesize in php.ini.
2 | UPLOAD_ERR_FORM_SIZE  | Size exceeds MAX_FILE_SIZE specified in HTML form.
3 | UPLOAD_ERR_PARTIAL    | 文件没有完整上传
4 | UPLOAD_ERR_NO_FILE    | 没有上传文件
5 | UPLOAD_ERROR_E        | As expliained by @Progman, removed in rev. 81792
6 | UPLOAD_ERR_NO_TMP_DIR | 找不到临时文件夹
7 | UPLOAD_ERR_CANT_WRITE | 磁盘不可写
8 | UPLOAD_ERR_EXTENSION  | File upload stopped by extension.

<form action="uploadFile.php" method="post" accept-charset="utf-8" enctype="multipart/form-data">
    请选择要上传的文件:
    <input type="file" name="myfile">
    <input type="submit" value="上传文件">
</form>
 
$_FILES文件变量

下面是上传一个图片然后打印整理出来的数据:

 
// name => 'QC8054R7QPGQ_1000x500.jpg'
// type => 'image/jpeg'
// tmp_name => '/Applications/MAMP/tmp/php/php1X5KZU'
// error => 0
// size => 229936
 
$_FILES上传的参数含义说明:

name:上传的文件的名称
type: 上传的文件的MIME类型
tmp_name:文件上传到服务器的临时路径
site:上传的文件的大小
error:上传的文件的错误码,0表示上传成功UPLOAD_ERR_OK

移动文件

移动文件方式一
上传文件到服务器端是在一个临时路径下,我们需要将文件移动到指定的目录下,我们可以通过下面的函数来实现移动:

 

// 将指定的文件移到的目录路径下
// 要求待移动的文件是通过HTTP POST上传的
bool move_uploaded_file ( string $filename , string $destination )
 
我们需要判断一下是否是通过HTTP POST上传的,下面的方法可以判断:

 
// 判断文件是否是通过HTTP POST上传的,如果是返回TRUE,否则返回FALSE
bool is_uploaded_file ( string $filename )
 
移动文件方式二

我们还可以通过下面的函数来实现移动文件:

// 参数一:待移动的文件
// 参数二:移动到的目标路径
bool copy ( string $source , string $dest [, resource $context ] )
 
处理上传

 
<?php
 
define('UPLOAD_PATH', 'Uploads');
 
$name = $_FILES['myfile']['name'];
$type = $_FILES['myfile']['type'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$error = $_FILES['myfile']['error'];
$size = $_FILES['myfile']['size'];
 
if ($error == UPLOAD_ERR_OK) {
    if (is_uploaded_file($tmp_name)) {
        move_uploaded_file($tmp_name, UPLOAD_PATH . '/' . $name);
    } else {
        if (is_file($tmp_name) && !copy($tmp_name, UPLOAD_PATH . '/' . $name)) {
            var_dump('ok');
        }
    }
} else {
    // 上传到服务器就已经出错了
    var_dump($error);
}
 
php.ini上传配置

假设我们要支持上传20M的文件,那么我们可以设置以下选项:

 
// 一定要设置为On,才能上传文件,若设置为Off,则服务器是接收不到文件数据的
file_uploads = On
 
// 指定上传文件到服务器的临时目录,默认为不打开的,可以不写
upload_tmp_dir = "d:/uploads_tmp"
 
// 支持上传的文件的最大为20M
upload_max_filesize = 20M
 
// 设置POST请求允许一次请求的最大值为100M
post_max_size = 100M
 
// 上传操作允许的最长时间,超过600秒则会停止脚本运行,0表示无限制
max_execution_time = 600
 
// PHP脚本解析请求数据所用的最大时间,默认为60秒,0表示无限制
max_input_time = 600
 
// 单个PHP脚本所能申请的最大内存,-1表示无限制!
memory_limit = 128M
 
上传文件错误码
UPLOAD_ERR_OK:代表上传成功
UPLOAD_ERR_EXTENSION:上传的文件被PHP扩展程序中断
UPLOAD_ERR_PARTIAL:文件只有部分被上传
UPLOAD_ERR_CANT_WRITE:文件写入失败
UPLOAD_ERR_FORM_SIZE:表单文件超过了post_max_size
UPLOAD_ERR_INI_SIZE:文件大小超过了限制上传的大小
UPLOAD_ERR_NO_FILE:没有文件被上传
UPLOAD_ERR_NO_TMP_DIR:找不到临时目录

客户端限制上传

我们可以通过隐藏域来实现限制上传的文件大小,同时可以通过accept来限制上传的文件的类型,如下所示:

 
<form action="uploadFile.php" method="post" accept-charset="utf-8" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="1024">
    请选择要上传的文件:
    <input type="file" name="myfile" accept="image/png">
    <input type="submit" value="上传文件">
</form>
 
服务端限制上传

我们可以通过在服务端来判断文件类型、文件大小,上传方式等来判断是否满足条件,然后才处理文件!

 
<?php
 
define('UPLOAD_PATH', 'Uploads');
define('MAX_FILE_SIZE', 2 * 1024 * 1024);
 
header('Content-type:text/html;Charset=utf-8');
 
$name = $_FILES['myfile']['name'];
$type = $_FILES['myfile']['type'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$error = $_FILES['myfile']['error'];
$size = $_FILES['myfile']['size'];
 
$allowExt = array('png', 'jpg', 'jpeg');
 
if ($error == UPLOAD_ERR_OK) {
    if ($size > MAX_FILE_SIZE) {
        exit('上传的文件过大');
    }
 
    // 取上传的文件的扩展类型
    $ext = pathinfo($name, PATHINFO_EXTENSION);
    if (!in_array($ext, $allowExt)) {
        exit('非法文件类型');
    }
 
    if (!is_uploaded_file($tmp_name)) {
        exit('文件不是HTTP POST上传过来的');
    }
 
    if (move_uploaded_file($tmp_name, UPLOAD_PATH . '/' . $name)) {
        echo '文件上传成功';
    } else {
        echo "文件上传失败";
    }
} else {
    // 上传到服务器就已经出错了
    var_dump($error);
}
 
忽略文件重名之类的问题,那些需要额外添加一些小处理哦!

二,上传文件类

<?php
 
ini_set('display_errors', 'On');
error_reporting(E_ALL);
header('Content-type:text/html;Charset=utf-8');
 
/**
* Class for Uploading a single image 
*/
class Upload {
    protected $fileName; /* eg, $_FILES['file'], the name is file. */
    protected $allowExt; /* Allow extension for uploading a file */
    protected $allowMIMEType;      /* Allow uploading file mine types */
    protected $fileMaxSize; /* Limit a uploading file size */
    protected $uploadPath;  /* The destination path */
    protected $isImageFlag;     /* Note that file is an image or not. */
    protected $errorMessage;   
    protected $fileExt;
    protected $fileInfos;
    protected $fileUniqueName;
    protected $fileDestPath;
 
    public function __construct($fileName = 'file', $uploadPath = './Uploads', $isImageFlag = true, $fileMaxSize = 1048576, $allowExt = array('png', 'jpg', 'jpeg', 'gif'), $allowMIMEType = array('image/png', 'image/jpeg', 'image/gif')) {
        $this->fileName = $fileName;
        $this->allowExt = $allowExt;
        $this->allowMIMEType = $allowMIMEType;
        $this->uploadPath = $uploadPath;
        $this->isImageFlag = $isImageFlag;
        $this->fileMaxSize = $fileMaxSize;
        // print_r($_FILES);
        $this->fileInfos = $_FILES[$fileName];
    }
 
    public function uploadFile() {
        if ($this->isValidExt()
            && $this->isValidMIMEType()
            && $this->isValidFileSize()
            && $this->isRealImage()
            && $this->isHTTPPOST()
            && !$this->hasError()) {
            $this->isUploadPathExist();
            $this->fileUniqueName = $this->getUniqueName();
            $this->fileDestPath = $this->uploadPath . '/' . $this->fileUniqueName . '.' . $this->fileExt;
// echo iconv('gb2312', 'UTF-8', $this->fileDestPath);
            if (@move_uploaded_file($this->fileInfos['tmp_name'], $this->fileDestPath)) {
                return $this->fileDestPath;
            } else {
                $this->errorMessage = '文件上传失败';
            }
        } else {
            $this->errorMessage = '文件上传失败';
        }
 
        exit('<span style="color:red">'.$this->errorMessage.'</span>');
    }
 
    protected function hasError() {
        $ret = true;
 
        if (!is_null($this->fileInfos)) {
            switch ($this->fileInfos['error']) {
                case UPLOAD_ERR_INI_SIZE:
                   $this->errorMessage = '文件大小超过PHP.ini文件中upload_max_filesize';
                   break;
                case UPLOAD_ERR_FORM_SIZE:
                    $this->errorMessage = '文件大小超过了表单中MAX_FILE_SIZE设置的值';
                    break;
                case UPLOAD_ERR_NO_TMP_DIR:
                    $this->errorMessage = '找不到临时文件目录';
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $this->errorMessage = '没有选择任何文件上传';
                    break;
                case UPLOAD_ERR_CANT_WRITE:
                    $this->errorMessage = '文件不可写';
                    break;
                case UPLOAD_ERR_PARTIAL:
                    $this->errorMessage = '只有部分文件被上传';
                    break;
                case UPLOAD_ERR_EXTENSION:
                    $this->errorMessage = '文件上传过程中被PHP扩展程序中断';
                    break;
                default:
                    $this->errorMessage = '';
                    $ret = false;
            }
        } else {
            $this->errorMessage = '文件上传出错';
        }
 
        return $ret;
    }
 
    protected function isValidFileSize() {
        if ($this->fileInfos['size'] > $this->fileMaxSize) {
            $this->errorMessage = '文件太大';
            return false;
        }
 
        return true;
    }
 
    protected function isValidExt() {
        $ext = pathinfo($this->fileInfos['name'], PATHINFO_EXTENSION);
        if (!in_array($ext, $this->allowExt)) {
            $this->errorMessage = '不支持的文件类型';
            return false;
        }
 
        $this->fileExt = $ext;
        return true;;
    }
 
    protected function isValidMIMEType() {
        $type = $this->fileInfos['type'];
 
        if (!in_array($type, $this->allowMIMEType)) {
            $this->errorMessage = '不支持的文件MIME类型';
            return false;
        }
 
        return true;
    }
 
    protected function isHTTPPOST() {
        if (!is_uploaded_file($this->fileInfos['tmp_name'])) {
            $this->errorMessage = '文件不是通过HTTP POST传上来的';
 
            return false;
        }
 
        return true;
    }
 
    protected function isRealImage() {
        if ($this->isImageFlag && !getimagesize($this->fileInfos['tmp_name'])) {
            $this->errorMessage = '文件不是图片';
            return false;
        }
 
        return true;
    }
 
    protected function isUploadPathExist() {
        if (!file_exists($this->uploadPath)) {
            mkdir($this->uploadPath, 0777, true);
        }
    }
 
    protected function getUniqueName() {
        return md5(microtime(true), true);
    }
}
 
$upload = new Upload('myfile');
if ($upload->uploadFile()) {
    echo "文件上传成功";
}

本文由正版必中一肖图发布于计算机网络,转载请注明出处:PHP一步步完结公文上传及上传文件类,php文件上

上一篇:广联云签订协议德雷斯顿中南主旨项目,项目管 下一篇:没有了
猜你喜欢
热门排行
精彩图文