PHP implements upload restrictions on file upload and download
Client restrictions
The code is as follows:
<!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>文件上傳(客戶(hù)端限制)</title> <meta charset="utf-8" /> </head> <body> <form action="upload2.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="101321" /> 請(qǐng)選擇您要上傳的文件: <input type="file" name="myFile" accept="image/jpeg,image/gif,text/html"/><br/> <input type="submit" value="上傳"/> </form> </body> </html>
The input attributes are used here to limit the size and type of uploaded files. But I personally feel that
1.html code is "visible"
2. It often doesn't work (I haven't found the reason, but because of the first one I also want to give up on it, just know it.
##Server Side Limitations
<?php header('content-type:text/html;charset=utf-8'); //接受文件,臨時(shí)文件信息 $fileinfo=$_FILES["myFile"];//降維操作 $filename=$fileinfo["name"]; $tmp_name=$fileinfo["tmp_name"]; $size=$fileinfo["size"]; $error=$fileinfo["error"]; $type=$fileinfo["type"]; //服務(wù)器端設(shè)定限制 $maxsize=10485760;//10M,10*1024*1024 $allowExt=array('jpeg','jpg','png','tif');//允許上傳的文件類(lèi)型(拓展名 $ext=pathinfo($filename,PATHINFO_EXTENSION);//提取上傳文件的拓展名 //目標(biāo)存放文件夾 $path="uploads"; if (!file_exists($path)) { //當(dāng)目錄不存在,就創(chuàng)建目錄 mkdir($path,0777,true);//創(chuàng)建目錄 chmod($path, 0777);//改變文件模式,所有人都有執(zhí)行權(quán)限、寫(xiě)權(quán)限、度權(quán)限 } //得到唯一的文件名!防止因?yàn)槲募嗤a(chǎn)生覆蓋 $uniName=md5(uniqid(microtime(true),true)).".$ext";//md5加密,uniqid產(chǎn)生唯一id,microtime做前綴 //目標(biāo)存放文件地址 $destination=$path."/".$uniName; //當(dāng)文件上傳成功,存入臨時(shí)文件夾,服務(wù)器端開(kāi)始判斷 if ($error===0) { if ($size>$maxsize) { exit("上傳文件過(guò)大!"); } if (!in_array($ext, $allowExt)) { exit("非法文件類(lèi)型"); } if (!is_uploaded_file($tmp_name)) { exit("上傳方式有誤,請(qǐng)使用post方式"); } //判斷是否為真實(shí)圖片(防止偽裝成圖片的病毒一類(lèi)的 if (!getimagesize($tmp_name)) {//getimagesize真實(shí)返回?cái)?shù)組,否則返回false exit("不是真正的圖片類(lèi)型"); } //move_uploaded_file($tmp_name, "uploads/".$filename); if (@move_uploaded_file($tmp_name, $destination)) {//@錯(cuò)誤抑制符,不讓用戶(hù)看到警告 echo "文件".$filename."上傳成功!"; }else{ echo "文件".$filename."上傳失敗!"; } }else{ switch ($error){ case 1: echo "超過(guò)了上傳文件的最大值,請(qǐng)上傳2M以下文件"; break; case 2: echo "上傳文件過(guò)多,請(qǐng)一次上傳20個(gè)及以下文件!"; break; case 3: echo "文件并未完全上傳,請(qǐng)?jiān)俅螄L試!"; break; case 4: echo "未選擇上傳文件!"; break; case 7: echo "沒(méi)有臨時(shí)文件夾"; break; } }Here, the specific implementation is commented, and you can actually try it yourself, which is very interesting
.