在上一篇教程中,我們探討了 PHP 自定義函數與陣列操作。本篇將深入講解移動互聯網開發中核心的文件上傳與下載機制,涵蓋客戶端配置、服務端處理、PHP 核心配置優化,以及常用文件系統函數與序列化技術。
要啟用文件上傳,HTML 表單必須滿足兩個必要條件:
enctype="multipart/form-data",告訴瀏覽器以二進制流形式傳輸文件數據。method="POST",只有 POST 請求才能攜帶文件數據體。此外,可選擇性添加一個隱藏字段限制單文件大小上限(單位為位元組):
<input type="hidden" name="MAX_FILE_SIZE" value="2097152"> <!-- 限制 2MB -->
文件上傳成功後,PHP 會自動填充 $_FILES 多維陣列,結構如下:
| 鍵名 | 說明 |
|---|---|
name | 客戶端原始文件名 |
type | MIME 類型(如 image/jpeg) |
tmp_name | 服務端臨時存儲路徑 |
error | 錯誤代碼(0 表示成功) |
size | 文件大小(位元組) |
以下配置直接影響上傳行為,建議根據業務需求調整:
| 指令 | 預設值 | 功能說明 |
|---|---|---|
| file_uploads | On | 是否允許 HTTP 文件上傳 |
| memory_limit | 8M | 腳本最大可用內存,防止失控腳本耗盡資源 |
| upload_max_filesize | 2M | 單個上傳文件最大值,必須小於 post_max_size |
| post_max_size | 8M | POST 請求體最大值,需大於 upload_max_filesize |
| upload_tmp_dir | NULL | 臨時文件存儲路徑,建議指定獨立目錄並賦予寫入權限 |




| 函數 | 用途 | 簽名 |
|---|---|---|
touch() | 設定文件訪問/修改時間 | bool touch(string $filename [, int $time [, int $atime]]) |
copy() | 複製文件 | bool copy(string $source, string $dest) |
rename() | 移動/重命名文件(跨分區亦可) | bool rename(string $oldname, string $newname) |
| 函數 | 用途 | 簽名 |
|---|---|---|
file_put_contents() | 原子化寫入字符串到文件(含鎖定、追加模式) | int file_put_contents(string $filename, mixed $data [, int $flags [, resource $context]]) |
file_get_contents() | 一次性讀取整個文件到字符串(支援偏移/長度) | string file_get_contents(string $filename [, bool $use_include_path [, resource $context [, int $offset [, int $maxlen]]]]) |
用於將複雜數據結構(陣列、對象)轉化為可存儲/傳輸的字符串格式。
string serialize(mixed $value)mixed unserialize(string $str)

microtime(bool $get_as_float):返回微秒級時間戳,性能分析必備。date_default_timezone_set(string $tz):設定預設時區(如 'Asia/Taipei'),避免警告。date_default_timezone_get():獲取當前預設時區。| 函數 | 功能 | 備註 |
|---|---|---|
strlen() | 獲取字節長度 | 多位元組字符需用 mb_strlen() |
strtolower() / strtoupper() | 大小寫轉換 | 區域相關,多語言建議用 mb_strtolower() |
ucfirst() / ucwords() | 首字母/每個單詞首字母大寫 | |
trim() / ltrim() / rtrim() | 去除首尾/左/右空白字符 | 可自定義字符列表 |
str_replace() / str_ireplace() | 大小寫敏感/不敏感替換 | 支援陣列批量替換 |
md5() | 計算 MD5 雜湊 | 不可逆,不建議用於密碼存儲 |
strpos() | 查找子串首次出現位置 | 嚴格判斷需用 !== false |