表单:
<html>
<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="2097152">
<input type="file" name="filename[]" multiple="multiple" accept="image/jpeg"><br/><br/>
<input type="submit" value="上传">
</form>
</body>
</html>
函数部分:
<?php
//判断是单文件还是多文件并且组合数组 function getFiles(){ $i=0;
foreach ($_FILES as $file) { if (is_array($file['name'])) {
foreach ($file['name'] as $key => $value) {
$files[$i]['name']=$file['name'][$key];
$files[$i]['type']=$file['type'][$key];
$files[$i]['tmp_name']=$file['tmp_name'][$key];
$files[$i]['size']=$file['size'][$key];
$files[$i]['error']=$file['error'][$key];
$i++;
} }elseif (is_string($file['name'])) {
$files[$i]=$file;
$i++;
# code...
} }
return $files;
} //上传文件函数 function uploadFiles($files){ $res=array();
//判断错误号
if($files['error']===UPLOAD_ERR_OK){ //判断文件大小
$maxsize=2097152;
if($files['size']>$maxsize){
$res['msg']=$files['name'].' 文件过大';
} //判断文件格式是否符合要求
$ext=strtolower(pathinfo($files['name'],PATHINFO_EXTENSION));
$extarray=['jpeg','jpg'];
if(!in_array($ext, $extarray)){
$res['msg']=$files['name'].' 格式不符合要求';
# code...
} //判断是否是真正的图片
$flag=true;
if($flag){
if(@!getimagesize($files['tmp_name'])){
$res['msg']=$files['name'].'不是真正的图片文件';
} } //判断是否是通过HTTP POST上传;
if(!is_uploaded_file($files['tmp_name'])){
$res['msg']=$files['name'].'不是通过HTTPPoSt上传';
}
if($res) return $res; //移动文件
$path='uploads';
if(!file_exists($path)){
mkdir($path,0777,true);
chmod($path,0777);
}
//唯一的文件名
$newname=md5(uniqid(microtime(true),true));
$destination=$path.'/'.$newname.'.'.$ext;
if(!move_uploaded_file($files['tmp_name'], $destination)){
$res['msg']=$files['name'].'文件移动失败';
}
$res['msg']=$files['name'].'上传成功';
$res['dest']=$destination;
return $res; }else{
switch ($files['error']) {
case 1:
$res['msg']=$files['name'].'文件超过了最大限制';
break;
case 2:
$res['msg']=$files['name'].'文件的大小超过了表单限制';
# code...
break;
case 3:
$res['msg']=$files['name'].'只有部分被上传';
# code...
break;
case 4:
$res['msg']='没有选择文件';
# code...
break;
case 6:
$res['msg']='找不到临时文件';
# code...
break;
case 7:
$res['msg']='系统错误';
# code...
break; }
return $res;
}
}
操作部分:
<?php
include('uploads_func.php'); $files=getFiles(); foreach ($files as $value) {
$res=uploadFiles($value);
echo $res['msg']."<br><br>";
# code...
}