您的位置:首页 > 编程语言 > PHP开发

PHP单文件上传的过程化函数封装

2016-04-08 21:01 746 查看
提交文件的页面:

upload.php

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="doAction3.php" method="post" enctype="multipart/form-data">
<!-- 在客户端可以设置表单MAX_FILE_SIZE限制的大小 -->
<!--<input type="hidden" name="MAX_FILE_SIZE" value="5*1024*1024">-->
请选择您要上传的文件:
<!-- 在客户端设置允许上传的文件类型 --><!-- 但是我们需要记住:客户端所做的任何限制都是不安全的 -->
<!--<input type="file" name="myFile" accept="image/jpeg,image/gif,image/png"/><br/>-->
<input type="file" name="myFile"/><br/>
<input type="submit" value="上传文件"/>
</form>
</body>
</html>


上传文件的函数 upload.func.php

<?php
/**
* Created by PhpStorm.
* User: DreamBoy
* Date: 2016/4/8
* Time: 20:13
*/
//$fileInfo = $_FILES['myFile'];
function uploadFile($fileInfo,$uploadPath = 'uploads',$allowExt=array('jpeg','jpg','png','gif'),$maxSize = 2097152, $flag=true) {
//判断错误号
if($fileInfo['error'] > 0) {
//匹配错误信息
switch($fileInfo['error']) {
case 1:
$mes = '上传文件超过了PHP配置文件中upload_max_filesize选项的值';
break;
case 2:
$mes = '超过了表单MAX_FILE_SIZE限制的大小';
break;
case 3:
$mes = '文件部分被上传';
break;
case 4:
$mes = '没有选择上传文件';
break;
case 6:
$mes = '没有找到临时目录';
break;
case 7:
case 8:
$mes = '系统错误';
break;
}
exit($mes);
}

$ext = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
//$allowExt = array('jpeg', 'jpg', 'png', 'gif');
if(!is_array($allowExt)) {
exit('系统错误');
}

//检测上传文件的类型
if(!in_array($ext, $allowExt)) {
exit('非法文件类型');
}
//$maxSize = 2097152; //2M
//检测上传文件大小是否符合规范
if($fileInfo['size']>$maxSize) {
exit('上传文件过大');
}
//检测图片是否为真实的图片类型
//$flag = true;
if($flag) {
if(!getimagesize($fileInfo['tmp_name'])) {
exit('不是真实图片类型');
}
}

//检测文件是否是通过HTTP POST方式上传上来的
if(!is_uploaded_file($fileInfo['tmp_name'])) {
exit('文件不是通过HTTP POST方式上传的');
}
//$uploadPath = 'uploads';
if(!file_exists($uploadPath)) {
mkdir($uploadPath, 0777, true);
chmod($uploadPath, 0777);
}
$uniName = md5(uniqid(microtime(true), true)) . '.' . $ext;
$destination = $uploadPath . '/' . $uniName;

if(!@move_uploaded_file($fileInfo['tmp_name'], $destination)) {
exit('文件移动失败');
}

//echo '文件上传成功';
return array(
'newName' => $destination,
'size' => $fileInfo['size'],
'type' => $fileInfo['type'],
);
}


提交表单的处理文件 doAction3.php

<?php
/**
* Created by PhpStorm.
* User: DreamBoy
* Date: 2016/4/8
* Time: 20:29
*/
header('content-type:text/html;charset=utf-8');
include_once 'upload.func.php';

$fileInfo = $_FILES['myFile'];
//$file = uploadFile($fileInfo);
//$file = uploadFile($fileInfo, 'MyFiles');

$allowExt = array('jpeg', 'jpg', 'png', 'gif', 'html', 'txt');
$file = uploadFile($fileInfo, 'MyFiles', false, $allowExt);
print_r($file);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: