PHP implements encapsulated upload function for file upload and download
Encapsulate the upload function
We encapsulate the above upload function into a function, the code is as follows:
fun_upload.php
<?php //定義一個(gè)uploadFile函數(shù) function uploadFile($fileInfo,$path,$allowExt,$maxSize){ //取出$_FILES中的數(shù)據(jù) $filename=$fileInfo["name"]; $tmp_name=$fileInfo["tmp_name"]; $size=$fileInfo["size"]; $error=$fileInfo["error"]; $type=$fileInfo["type"]; //取出文件路徑中文件的類型的部分 $ext=pathinfo($filename,PATHINFO_EXTENSION); //確定是否存在存放圖片的文件夾,沒有則新建一個(gè) if (!file_exists($path)) { //當(dāng)目錄不存在,就創(chuàng)建目錄 mkdir($path,0777,true);//創(chuàng)建目錄 chmod($path, 0777);//改變文件模式,所有人都有執(zhí)行權(quán)限、寫權(quán)限、度權(quán)限 } //得到唯一的文件名!防止因?yàn)槲募嗤a(chǎn)生覆蓋 $uniName=md5(uniqid(microtime(true),true)).'.'.$ext; //目標(biāo)存放文件地址 $destination=$path."/".$uniName; //當(dāng)文件上傳成功,存入臨時(shí)文件夾,服務(wù)器端開始判斷 if ($error==0) { if ($size>$maxSize) { exit("上傳文件過大!"); } if (!in_array($ext, $allowExt)) { exit("非法文件類型"); } if (!is_uploaded_file($tmp_name)) { exit("上傳方式有誤,請使用post方式"); } //判斷是否為真實(shí)圖片(防止偽裝成圖片的病毒一類的 if (!getimagesize($tmp_name)) {//getimagesize真實(shí)返回?cái)?shù)組,否則返回false exit("不是真正的圖片類型"); } if (@move_uploaded_file($tmp_name, $destination)) {//@錯(cuò)誤抑制符,不讓用戶看到警告 echo "文件".$filename."上傳成功!"; }else{ echo "文件".$filename."上傳失敗!"; } }else{ switch ($error){ case 1: echo "超過了上傳文件的最大值,請上傳2M以下文件"; break; case 2: echo "上傳文件過多,請一次上傳20個(gè)及以下文件!"; break; case 3: echo "文件并未完全上傳,請?jiān)俅螄L試!"; break; case 4: echo "未選擇上傳文件!"; break; case 7: echo "沒有臨時(shí)文件夾"; break; } } return $destination; }
The form page adopts the previous one:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="format-detection" content="telephone=no" /> <title>文件上傳(客戶端限制)</title> <meta charset="utf-8" /> </head> <body> <form action="upload3.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="101321" /> 請選擇您要上傳的文件: <input type="file" name="myFile" accept="image/jpeg,image/gif,text/html"/><br/> <input type="submit" value="上傳"/> </form> </body> </html>
Submission processing page
upload3.php
<?php header('content-type:text/html;charset=utf-8'); //初始化相關(guān)變量 $fileInfo=$_FILES["myFile"]; $maxSize=10485760;//10M,10*1024*1024 $allowExt=array('jpeg','jpg','png','tif'); $path="uploads"; //引入前面封裝了的上傳函數(shù)fun_upload.php include_once 'fun_upload.php'; uploadFile($fileInfo, $path, $allowExt, $maxSize);
The comments are very detailed. You can copy them to your local computer to test and learn at the same time.
is encapsulated. We can call it directly after using it. Isn’t it very convenient? We will use it in the next section of multi-file upload. This encapsulated function