<?php function check($file, $folder='uploads', $prefix=''){ # 判断上传目录是否存在 if(!is_dir(dirname(__FILE__)."/{$folder}")){ mkdir(dirname(__FILE__)."/{$folder}"); } # 上传文件重命名 $newName= uniqid($prefix,true).strrchr($file['name'],'.'); $newDir= "{$folder}/".$newName; # 文件拓展名验证 $info= finfo_open(FILEINFO_MIME_TYPE); $ext= finfo_file($info, $file['tmp_name']); $allow= array('image/jpeg','image/png','image/gif'); if(!in_array($ext,$allow)){ return '只能上传 '.implode(' , ',$allow).' 等文件格式'; } # 验证文件大小是否越界 $fileSize= ini_get('upload_max_filesize'); if(substr($fileSize, -1, 1)== 'k'){ $fileSize= (integer)$fileSize* 1024; }elseif(substr($fileSize, -1, 1)== 'M'){ $fileSize= (integer)$fileSize* 1024* 1024; }elseif(substr($fileSize, -1, 1)== 'G'){ $fileSize= (integer)$fileSize* 1024* 1024* 1024; }elseif(substr($fileSize, -1, 1)== 'T'){ $fileSize= (integer)$fileSize* 1024* 1024* 1024* 1024; } if($file['size']> $fileSize){ return '文件大小不能超过'.number_format($fileSize/1024, 1).'K'; } # 验证是否是http上传 if(!is_uploaded_file($file['tmp_name'])){ return '文件不是HTTP POST上传的<br>'; } # 上传错误码 if($file['error']> 0){ switch($file['error']) { case 1: return '文件大小超过了php.ini中允许的最大值,最大值是:'.ini_get('upload_max_filesize'); case 2: return '文件大小超过了表单允许的最大值'; case 3: return '只有部分文件上传'; case 4: return '没有文件上传'; case 6: return '找不到临时文件'; case 7: return '文件写入失败'; default: return '未知错误'; } } # 文件上传 if(move_uploaded_file($file['tmp_name'], $newDir)){ return "上传成功"; } } if(!empty($_POST)) { echo check($_FILES['userfile']); } ?>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>文件上传</title> </head> <body> <form action="upload.php" enctype="multipart/form-data" method="post"> <input type="hidden" name="MAX_FILE_SIZE" value="30000000"> 选择文件:<input type="file" name="userfile"> <input type="submit" value="上传文件"> </form> </body> </html>