首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 多檔案上傳至伺服器完整實作

     編輯:PHP 綜合知識

實例說明

上傳圖片至伺服器是開發必備功能,不僅能共享圖片、提高訪問量、豐富內容。本例講解 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 限制大小,必須置於檔案域之前才生效。

設計流程

(1)index.php - 上傳表單

<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>

(2)index_ok.php - 處理上傳與入庫

<?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>";
}
?>

進階技巧:偽靜態隱藏 PHP 副檔名

  1. 修改 Apache httpd.conf:啟用 LoadModule rewrite_module modules/mod_rewrite.so,將 AllowOverride 改為 All,重啟 Apache。
  2. 根目錄建立 .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 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved