PHP development of multiple files uploaded to MySql database (2)
First of all, we need to create an HTML page using the <form> form
<body> <form action="tu5.php" method="post" enctype="multipart/form-data"> 上傳文件:<br><br> <input type="hidden" name="MAX_FILE_SIZE" value="1000000"> 第一張圖:<input type="file" name='myfile[]'><br><br> 第二張圖:<input type="file" name='myfile[]'><br><br> <input style="margin-left: 8%;" type="submit" value="上傳"> </form> </body>
Here we demonstrate uploading 2 images at a time.
You can select two pictures by clicking the two "Select File" buttons, and then click "Upload" to upload the two pictures at once.
Show the complete PHP backend function code:
<?php echo "<pre>"; echo "<hr/>"; //1.獲取上傳文件信息 $upfile = $_FILES["myfile"]; $typelist = array("image/jpeg","image/jpg","image/png","image/gif"); //定義允許的類型 $path="uploads/"; //定義一個上傳過后的目錄 //重新組裝上傳文件的數(shù)據(jù),以便依次上傳 $uploadFiles = array(); foreach($upfile as $key =>$value) { foreach($value as $k => $v){ $uploadFiles[$k][$key]=$v; } } //遍歷上傳 foreach($uploadFiles as $k => $v) { //2. 過濾上傳文件的錯誤號 if ($v['error'] > 0) { //獲取錯誤信息 switch ($v['error']) { case 1: $info = "上傳的文件超過了 php.ini 中 upload_max_filesize 選項限制的值。"; break; case 2: $info = "上傳文件的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項指定的值。"; break; case 3: $info = "文件只有部分被上傳。"; break; case 4: $info = "沒有文件被上傳。 "; case 6: $info = "找不到臨時文件夾。"; break; case 7: $info = "文件寫入失敗"; break; } die("上傳文件{$k}錯誤,原因:" . $info); } //3. 本次上傳文件到小的過濾(自己選擇) if ($v['size'] > 100000) { die('上傳文件{$k}大小超出限制!'); } //4. 類型過濾 if (!in_array($v["type"], $typelist)) { die("上傳文件{$k}類型非法!" . $v["type"]); } //5. 上傳后的文件名定義(隨機獲取一個文件名(保持后綴名不變)) $fileinfo = pathinfo($v["name"]);//解析上傳文件名字 do{ $newfile = date("Y-m-d,H-i-s") . rand(1000, 9999) . "." . $fileinfo["extension"]; } while (file_exists($path . $newfile)); //6. 執(zhí)行文件上傳 //判斷是否是一個上傳的文件 if (is_uploaded_file($v["tmp_name"])) { //執(zhí)行文件上傳(移動上傳文件) if (move_uploaded_file($v["tmp_name"], $path . $newfile)) { //echo "文件{$K}上傳成功!"; //執(zhí)行寫入數(shù)據(jù)庫操作 $link = mysqli_connect('localhost','root','root') or die("數(shù)據(jù)庫連接失?。?quot;); $db = mysqli_select_db($link,'test'); mysqli_set_charset($link,'utf8'); $filepath = $path.$newfile; $name = $v['name']; $size = $v['size']; $sql = "insert into img(id,name,size,pic) value(null,'$name','$size','$filepath')"; mysqli_query($link,$sql); mysqli_close($link); } else { die("上傳文件{$k}失敗"); } } else { die("不是一個上傳文件!"); } } ?>