<?php
if($_FILES){
$srcname=$_FILES['headimg']['name'];
$ext=array_pop(explode('.',$srcname)); //后缀
$tmp=$_FILES['headimg']['tmp_name'];
$error=$_FILES['headimg']['error']; //错误码
$dstdir='./public/uploads/';
$filesize=$_FILES['headimg']['size']; //文件大小
$imgname=substr(md5(time().mt_rand()),3,15).'.'.$ext;
$dst=$dstdir.$imgname;
try {
if($error!==0){
$error='您没有选择上传文件';
throw new Exception($error);
}
//限制大小 1M=1*1024*1024字节
$size=1*1024*1024;
if($filesize>$size){
$error = '文件大小不允许超过1M';
throw new Exception($error);
}
//限制类型
$type=array('jpg','png','gif');
if(!in_array($ext,$type)){
$error = '不允许该文件类型';;
throw new Exception($error);
}
if(move_uploaded_file($tmp, $dst)){
echo '文件上传成功';
}else{
echo '文件上传失败';
}
} catch (Exception $e) {
$error=$e->getMessage();
echo "<script>alert('{$error}');location='index.php'</script>";
}
}else{
echo "<script>alert('文件大小超过php限制');location='index.php'</script>";
}
?>