這篇文章介紹的內容是關於php下載的功能,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
upload.php開始
<?phpfunction upload_file($fileInfo,$uploadPath='./uploads',$imageFlag=true,$allowExt=array('jpeg','jpg','png','gif'),$maxSize=209708){define('UPLOAD_ERRS',[ 'upload_max_filesize'=>'超過了PHP設定檔中upload_max_filesize選項的值', 'form_max_size'=>'超過了表單MAX_FILE_SIZE選項的值', 'upload_file_partial'=>'檔案部分被上傳', 'no_upload_file_select'=>'沒有選擇上傳檔案', 'upload_system_error'=>'系統錯誤', 'no_allow_ext'=>'非法檔案類型', 'exceed_max_size'=>'超出允許上傳的最大值', 'not_true_image'=>'檔案不是真實圖片', 'not_http_post'=>'檔案不是通過HTTP POST方式上傳上來的', 'move_error'=>'檔案移動失敗']);//檢測是否上傳是否有錯誤 if($fileInfo['error']===UPLOAD_ERR_OK){ //檢測上傳檔案類型 $ext=strtolower(pathinfo($fileInfo['name'],PATHINFO_EXTENSION)); if(!in_array($ext,$allowExt)){ echo UPLOAD_ERRS['no_allow_ext']; return false; } //檢測上傳檔案大小是否符合規範 if($fileInfo['size']>$maxSize){ echo UPLOAD_ERRS['exceed_max_size']; return false; } //檢測是否是真實圖片 if($imageFlag){ if(@!getimagesize($fileInfo['tmp_name'])){ echo UPLOAD_ERRS['not_true_image']; return false; } } //檢測檔案是否通過HTTP POST方式上傳上來的 if(!is_uploaded_file($fileInfo['tmp_name'])){ return UPLOAD_ERRS['not_http_post']; } //檢測目標目錄是否存在,不存在則建立 if(!is_dir($uploadPath)){ mkdir($uploadPath,0777,true); } //產生唯一檔案名,防止重名產生覆蓋 $uniName=md5(uniqid(microtime(true),true)).'.'.$ext; $dest=$uploadPath.DIRECTORY_SEPARATOR.$uniName; //移動檔案 if(@!move_uploaded_file($fileInfo['tmp_name'],$dest)){ echo UPLOAD_ERRS['move_error']; return false; } echo '檔案上傳成功'; return $dest; }else{ switch($fileInfo['error']){ case 1: // $mes='超過了PHP設定檔中upload_max_filesize選項的值'; $mes=UPLOAD_ERRS['upload_max_filesize']; break; case 2: $mes=UPLOAD_ERRS['form_max_size']; break; case 3: $mes=UPLAOD_ERRS['upload_file_partial']; break; case 4: $mes=UPLOAD_ERRS['no_upload_file_select']; break; case 6: case 7: case 8: $mes=UPLAOD_ERRS['upload_system_error']; break; } echo $mes; return false; }}?>
upload.php結束
html的開始<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>Document</title></head><body> <!-- <a href="http://localhost:8081/download.php?filename=5.html">下載5.html</a> --> <h1>檔案上傳</h1> <form action="http://localhost:8081/doUpload.php" method='post' enctype="multipart/form-data"> <input type="file" name="myFile" id=""> <input type="submit" value="立即上傳"> </form></body></html>html的結束doUpload.php的開始<?php require_once('upload.php'); $fileInfo=$_FILES['myFile'];var_dump(upload_file($fileInfo));?>
doUpload.php的結束