up.php
<!DOCTYPE html>
<html>
<head>
<title>文件上传www.linuxidc.com</title>
<meta charset="utf-8">
</head>
<body>
<form action="hendle.php" method="post" enctype="multipart/form-data" >
请选择要上传的文件:
<input type="file" name="myFile" /><br />
<input type="submit" value="上传文件" />
</form>
</body>
</html>
hendle.php
<?php
header('content-type:text/html;charset=utf-8');
include_once 'upload.func.php';
//上传封装函数的五个参数:$fileInfo,$maxsize,$uploadPath,$allowExt,$flag
$fileInfo=$_FILES['myFile'];
// print_r($_FILES);
// exit;
// $filename=$_FILES['myFile']['name'];
// $type=$_FILES['myFile']['type'];
// $tmp_name=$_FILES['myFile']['tmp_name'];
// $size=$_FILES['myFile']['size'];
// $error=$_FILES['myFile']['error'];
$maxsize=2097152;
$uploadPath='uploads';
$allowExt=array('jpeg','jpg','png','gif');
$flag=true;
$newName=uploadFile($fileInfo,$maxsize,$uploadPath,$allowExt,$flag);
echo "上传成功,路径为:".$newName;
?>
upload.func.php
<?php
function uploadFile($fileInfo,$maxsize,$uploadPath,$allowExt,$flag){
//判断错误号
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);
//检测上传文件的类型
if (!@in_array($ext,$allowExt)) {
exit('非法文件类型');
}
//检测上传文件的大小是否符合规范
//$maxsize=2097152;//默认值为2M
if ($fileInfo['size']>$maxsize) {
exit('上传文件超过'.($maxsize/1024/1024).'M');
}
//检测图片是否为真实图片类型,立flag,若不需要检测,则设置flag为false即可
//$flag=true;
if($flag){
if (!@getimagesize($fileInfo['tmp_name'])) {
exit('不是真实的图片类型');
}
}
//检测文件是否通过HTTP POST方式上传的
if (!@is_uploaded_file($fileInfo['tmp_name'])) {
exit('文件不是通过HTTP POST方式上传的');
}
//存储目录
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']
// };
return $destination;
}
?>