php實現多圖上傳功能
阿新 • • 發佈:2018-11-10
總共三個文化 index.html conn.php upload.php
index.html程式碼:
<html> <head>上傳檔案</head> <body> <form method="post" action="upload.php" enctype="multipart/form-data"> <input name='uploads[]' type="file" multiple> <input type="submit" name="uploadpic" value="上傳"> </form> </body> </html>
conn.php程式碼:
<?php $conn=mysql_connect("localhost","root","root") or die("資料庫伺服器連線錯誤".mysql_error()); mysql_select_db("test2",$conn) or die("資料庫訪問錯誤".mysql_error()); mysql_query("set character utf8"); mysql_query("set names utf8");
upload.php程式碼:
<?php test2
include("conn.php");
$uploadfile; // 圖片的名字
if($_POST['uploadpic']=='上傳'){
$dest_folder = "D:/phpStudy/WWW/picture/"; //上傳圖片儲存的路徑 圖片放在跟你upload.php同級的picture資料夾裡
$arr=array(); //定義一個數組存放上傳圖片的名稱方便你以後會用的。
$count=0;
if(!file_exists($dest_folder)){
mkdir($dest_folder,700); // 建立資料夾,並給予最高許可權
}
$tp = array("image/gif","image/pjpeg","image/jpeg","image/png"); //檢查上傳檔案是否在允許上傳的型別
foreach ($_FILES["uploads"]["error"] as $key => $error){
if(!in_array($_FILES["uploads"]["type"][$key],$tp)){
echo "<script language='javascript'>";
echo "alert(\"檔案型別錯誤!\");";
echo "</script>";
exit;
}
if($error == UPLOAD_ERR_OK){
$tmp_name = $_FILES["uploads"]["tmp_name"][$key];
$a=explode(".",$_FILES["uploads"]["name"][$key]); //擷取檔名跟字尾
// $prename = substr($a[0],10); //如果你到底的圖片名稱不是你所要的你可以用擷取字元得到
$prename = $a[0];
$name = date('YmdHis').mt_rand(100,999).".".$a[1]; // 檔案的重新命名 (日期+隨機數+字尾)
$uploadfile = $dest_folder.$name; // 檔案的路徑
move_uploaded_file($tmp_name, $uploadfile);
$arr[$count]=$uploadfile;
$query="insert into product(name,tupian,pLike) values('$prename','$uploadfile','0')"; // 插入到資料庫
$res=mysql_query($query);
if($res)
echo $prename."chenggong<br/>";
echo $uploadfile."<br />";
$count++;
}
}
echo "總共".$count."檔案";
}
我們建的表為:
開始執行程式:得到如下結果