上傳圖片至伺服器是開發必備功能,不僅能共享圖片、提高訪問量、豐富內容。本例講解 POST 方式實現多圖片上傳(4 張以內)。
name="files[]")array_filter() 搭配回呼函式移除陣列空元素,支援任意數量上傳array_filter() 語法:array array_filter(array input[, callback callback])。若回呼函式回傳 TRUE,該元素保留於結果陣列且鍵名不變。若無回呼函式,刪除所有等值 FALSE 的元素。
回呼函式 check():
function check($var) {
return ($var != "");
}
注意: 表單必須設定
enctype="multipart/form-data"。若用隱藏域MAX_FILE_SIZE限制大小,必須置於檔案域之前才生效。
<table width="750" border="0" cellspacing="0" cellpadding="0">
<form action="index_ok.html" method="post" enctype="multipart/form-data" name="form1">
<tr>
<td width="100" height="25" align="right" class="STYLE1">內容1:</td>
<td width="150" align="center"><input name="files[]" type="text" id="files[]" size="15"></td>
<td align="left"><input name="picture[]" type="file" id="pcture[]" size="30"></td>
</tr>
<tr>
<td height="25" align="right" class="STYLE1">內容2:</td>
<td width="center"><input name="files[]" type="text" id="files[]" size="15"></td>
<td align="left"><input name="picture[]" type="file" id="pcture[]" size="30"></td>
</tr>
<tr>
<td colspan="3" align="center">
<input type="image" name="imageField" src="images/bg_09.jpg">
<input type="image" name="imgeField2" src="images/bg_11.jpg">
</td>
</tr>
</form>
</table>
<?php
header("Content-type:text/html;charset=UTF-8");
include "conn/conn.php";
if ($_POST['files'] != "") {
if (!is_dir("./upfile")) {
mkdir("./upfile");
}
$data = date("Y-m-d H:m:s");
function check($var) {
return ($var != "");
}
$files = array_filter($_POST["files"], "check");
$array = array_filter($_FILES["picture"]["name"], "check");
foreach ($array as $key => $value) {
$path = 'upfile/' . time() . $key . strtolower(strstr($value, "."));
move_uploaded_file($_FILES["picture"]["tmp_name"][$key], $path);
$query = "insert into tb_up_file(file_test, data, file_name) values ('$path', '$data', '$files[$key]')";
$result = mysql_query($query);
}
echo "<script>alert('圖片上傳成功'); window.location.href='index.html';</script>";
}
?>
httpd.conf:啟用 LoadModule rewrite_module modules/mod_rewrite.so,將 AllowOverride 改為 All,重啟 Apache。.htaccess:RewriteEngine On
RewriteRule ^index.html$ index.php
RewriteRule ^index_ok.html$ index_ok.php
RewriteRule ^index-([0-9]+)-([0-9]+)-([0-9]+)\.html$ index.php?vv=$1&ljjl=$2&page=$3 [L]
透過正則匹配隱藏 PHP 副檔名與參數傳遞。
希望本文對大家的 PHP 程式設計有所幫助。