PHP一步步实现文件上传及上传文件类
一,比较简单的实现文件上传
文件上传原理:文件上传原理:将客户端的文件先上传到服务器端,然后再将服务器端的临时文件移动到指定的目录。
客户端配置:要上传文件,我们需要采用表单,并且表单发送的形式来POST请求,而且要求将enctype设置为multipart/form-data,总结上传的条件如下:
浏览器表单页面:表单发送方式为post,指定enctype=multipart/form-data,客户端的代码:
- <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 ] )
处理上传:
- 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');
- } //phpfensi.com
- }
- } 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>
服务端限制上传:
我们可以通过在服务端来判断文件类型、文件大小,上传方式等来判断是否满足条件,然后才处理文件!
- 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);
- }
忽略文件重名之类的问题,那些需要额外添加一些小处理哦!
二,上传文件类
- 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 >'.$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 "文件上传成功";
- }