<?php /* * 文件上传函数 */ function upload_single($file, $allow_type, $path, &$error, $allow_format=array(), $max_size=2000000){ //判断文件是否有效 if(!(is_array($file)&&isset($file["error"]))){ $error="上传文件无效"; return false; } //判断保存路径是否有效 if(!is_dir($path)){ $error="路径错误!"; return false; } //判断文件上传过程中是都出错 switch ($file["error"]){ case 1: case 2: $error="文件超出服务器应许大小"; return false; case 3: $error="文件只上传部分"; return false; case 6: case 7: $error="文件保存失败"; return false; } //判断mime类型 if(!in_array($file["type"], $allow_type)){ print_r($file["type"]."<->".$allow_type); $error="当前文件不允许上传12"; return false; } //判断后缀名是否正确 $ext=ltrim(strrchr($file["name"],"."), "."); if(!in_array($ext, $allow_format)&&!empty($allow_format)){ $error="上传文件是不允许上传的后缀名"; return false; } //判断当前文字是否满足这个函数的最大上传值 if($file["size"]>$max_size){ $error="上传文件过大"; return false; } //构建名字:随机构造 $full_name=strstr($file["type"], "/").date("YYYYmmdd"); for($i=0;$i<4;++$i){ $full_name.=chr(mt_rand(65,90)); } //拼凑后缀 $full_name.='.'.$ext; //移动到指定目录 if(!is_uploaded_file($file["tmp_name"])){ $error="错误, 不是上传文件"; return false; } if(move_uploaded_file($file["tmp_name"], $path.'/'.$full_name)){ return $full_name; }else{ $error="文件移动失败"; return false; } } //提供数据 $file=$_FILES["image"]; $path="image/"; $allow_format=array("JPG", "JPEG"); $allow_type=array("image/jpeg", "/image/jpg"); $max_size=80000000; $error; if(upload_single($file, $allow_type, $path, $error, $allow_format, $max_size)){ echo "上传成功!"; }else{ echo $error; }