abstrait://上傳方法 /** * 單文件上傳操作 * @param $fileInfo // 上傳的文件信息 * @param string $uploadPath // 上傳的指定目錄
//上傳方法 /** * 單文件上傳操作 * @param $fileInfo // 上傳的文件信息 * @param string $uploadPath // 上傳的指定目錄 * @param array $allowExt // 上傳的文件類型 * @param int $maxSize // 上傳的最大值 * @return string 提示信息 */ function upload_file($fileInfo,$uploadPath='./upload',$allowExt=['png','jpg','jpeg','gif','txt','html'],$maxSize = 1000000) { // 判斷上傳錯(cuò)誤號(hào) if($fileInfo['error'] === 0){ // 獲取文件后綴 $ext = strtolower(pathinfo($fileInfo['name'],PATHINFO_EXTENSION)); // 判斷文件類型 if (!in_array($ext,$allowExt)){ return '非法文件類型!'; } // 判斷文件大小 if ($fileInfo['size']>$maxSize){ return '超出文件上傳的最大值'; } // 判斷文件上傳方式 if (!is_uploaded_file($fileInfo['tmp_name'])){ return '非法上傳!'; } // 判斷需要移動(dòng)到的目錄是否存在 if(!is_dir($uploadPath)){ mkdir($uploadPath,0777,true); } // 生成唯一的文件名 uniqid 生成唯一id microtime 返回當(dāng)前unix時(shí)間戳中的微妙 $uniName = md5(uniqid(microtime(),true)).".".$ext; // 拼接路徑以及文件名 $dast = $uploadPath."/".$uniName; // 將文件移動(dòng)到指定目錄 if (!move_uploaded_file($fileInfo['tmp_name'],$dast)){ return '文件上傳失??!'; } return '文件上傳成功!'; }else{ switch ($fileInfo['error']){ case 1: $res = '上傳的文件超過了 php.ini 中 upload_max_filesize 選項(xiàng)限制的值!'; break; case 2: $res = '上傳文件的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項(xiàng)指定的值!'; break; case 3: $res = '文件只有部分被上傳!'; break; case 4: $res = '沒有文件被上傳!'; break; case 6: case 7: $res = '系統(tǒng)錯(cuò)誤!'; break; } return $res; } }
//html上傳頁面 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上傳</title> </head> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="MyFile"> <input type="submit" value="上傳"> </form> </body> </html>
//upload.php <?php /** * Created by PhpStorm. * User: lenovo * Date: 2019/3/31 * Time: 16:21 */ include 'function.php'; $fileInfo = $_FILES['MyFile']; var_dump(upload_file($fileInfo));
//下載操作 /** * 文件下載操作 * @param $filename // 需要下載的文件名 */ function dow_file($filename) { // 告訴瀏覽器返回文件的大小 header('Accept-Length:'.filesize($filename)); // 告訴瀏覽器文件作為復(fù)件處理,并告訴瀏覽器下載完的文件名 header('Content-Disposition:attachment;filename='.basename($filename)); // 輸出文件 readfile($filename); } dow_file('6.jpg');
Professeur correcteur:查無此人Temps de correction:2019-04-01 09:54:59
Résumé du professeur:完成的不錯(cuò)。上傳一定要把文件類型給判斷了。不能讓其他類型的文件也上傳。