PHP はファイルのアップロードとダウンロードのために複數(shù)のファイルのアップロードを?qū)g裝します
1 つのファイルを使用して
フォーム ページをカプセル化します:
index4.php
<!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" /> <meta charset="utf-8" /> <title>多文件上傳</title> </head> <body> <form action="upload4.php" method="post" enctype="multipart/form-data"> 請(qǐng)選擇您要上傳的文件:<input type="file" name="myFile1" /><br/> 請(qǐng)選擇您要上傳的文件:<input type="file" name="myFile2" /><br/> 請(qǐng)選擇您要上傳的文件:<input type="file" name="myFile3" /><br/> 請(qǐng)選擇您要上傳的文件:<input type="file" name="myFile4" /><br/> <input type="submit" value="上傳"/> </form> </body> </html>
アップロード ハンドラー
upload4.php
<?php //echo "<pre>"; //print_r($_FILES); //echo "</pre>"; //exit; header('content-type:text/html;charset=utf-8'); include_once 'fun_upload.php'; foreach ($_FILES as $fileInfo){ $file[]=uploadFile($fileInfo); }
を印刷してみると、$_FILES が 2 つあることがわかります。 -次元配列は、それを走査するだけで十分です。
カプセル化されたアップロード関數(shù)を変更し、いくつかのデフォルト値を與える必要があります
function UploadFile($fileInfo,$path="uploads",$allowExt=array('jpeg','jpg','png) ', 'tif'),$maxSize=10485760){
コードは次のとおりです:
fun_upload.php
<?php function uploadFile( $fileInfo,$path="uploads",$allowExt=array('jpeg','jpg','png','tif'),$maxSize=10485760 ){ $filename=$fileInfo["name"]; $tmp_name=$fileInfo["tmp_name"]; $size=$fileInfo["size"]; $error=$fileInfo["error"]; $type=$fileInfo["type"]; //服務(wù)器端設(shè)定限制 $ext=pathinfo($filename,PATHINFO_EXTENSION); //目的信息 if (!file_exists($path)) { mkdir($path,0777,true); chmod($path, 0777); } $uniName=md5(uniqid(microtime(true),true)).'.'.$ext; $destination=$path."/".$uniName; if ($error==0) { if ($size>$maxSize) { exit("上傳文件過(guò)大!"); } if (!in_array($ext, $allowExt)) { exit("非法文件類型"); } if (!is_uploaded_file($tmp_name)) { exit("上傳方式有誤,請(qǐng)使用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 "超過(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; } } return $destination; }
この方法で、単純な複數(shù)ファイルのアップロードを?qū)g裝できます