PHP 擁有龐大的內建函式庫,涵蓋資料庫、檔案系統、網路、圖像、加密、壓縮等領域,讓開發者無需安裝額外擴充即可完成複雜任務。本文深入四大進階主題:模板系統、效能優化、檔案上傳、郵件發送。
<!-- include/header.php -->
<header>
<h1>= $siteTitle ?? 'My Site' ?></h1>
<nav><a href="/index.php">首頁</a> | <a href="/about.php">關於</a></nav>
</header>
<!-- index.php -->
<?php
$siteTitle = '首頁';
include 'include/header.php';
?>
<main>歡迎內容...</main>
<?php include 'include/footer.php'; ?>
資料庫帳密等敏感資訊**絕不可**直接寫在 Web 目錄下的 PHP 檔案。若 Apache 解析失敗,原始碼將直接暴露。
// 目錄結構
/var/www/html/ <-- DocumentRoot (公開可存取)
/var/www/private/ <-- 私有目錄 (Web 不可直接存取)
└── config/
└── db.php // 只有 PHP include 可讀取
<?php
// /var/www/private/config/db.php
return [
'host' => 'localhost',
'dbname' => 'myapp',
'user' => 'app_user',
'pass' => 'strong_password_here',
];
<?php
// 公開腳本中安全引入
$dbConfig = include '/var/www/private/config/db.php';
$pdo = new PDO(
"mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset=utf8mb4",
$dbConfig['user'],
$dbConfig['pass']
);
關鍵設定:php.ini 的 include_path 加入私有目錄:
; Unix/Linux
include_path = ".:/var/www/private"
; Windows
include_path = ".;C:\www\private"
純動態頁面每請求都執行 PHP、查詢資料庫、渲染模板。對高流量頁面(首頁、列表頁),可採用「定期靜態化」策略:
generate_homepage.php 執行完整邏輯,輸出 HTML 存為 cache/index.html。index.html,完全繞過 PHP。<?php
// generate_homepage.php
require_once 'bootstrap.php'; // 載入設定、資料庫、模板引擎
$articles = $articleRepo->findLatest(10);
$html = $twig->render('homepage.twig', ['articles' => $articles]);
$cacheFile = __DIR__ . '/../public/cache/index.html';
file_put_contents($cacheFile, $html, LOCK_EX);
echo "首頁靜態化完成:" . date('Y-m-d H:i:s') . "\n";
location / {
try_files /cache/index.html $uri $uri/ /index.php?$query_string;
}
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880"> <!-- 5MB 客戶端提示 -->
<input type="file" name="avatar" accept="image/*" required>
<button type="submit">上傳頭像</button>
</form>
<?php
// upload.php
declare(strict_types=1);
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
const UPLOAD_DIR = __DIR__ . '/../storage/uploads/';
session_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => '', 'data' => null];
// 1. 檢查請求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$response['message'] = '僅接受 POST 請求';
echo json_encode($response);
exit;
}
// 2. 檢查上傳錯誤
if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
$response['message'] = '檔案上傳失敗,錯誤代碼:' . ($_FILES['avatar']['error'] ?? '未知');
echo json_encode($response);
exit;
}
$file = $_FILES['avatar'];
// 3. 驗證檔案大小
if ($file['size'] > MAX_SIZE) {
$response['message'] = '檔案過大,限制 5MB';
echo json_encode($response);
exit;
}
// 4. 驗證 MIME 類型(需安裝 fileinfo 擴充)
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if (!in_array($mime, ALLOWED_TYPES, true)) {
$response['message'] = '不支援的檔案類型:' . $mime;
echo json_encode($response);
exit;
}
// 5. 產生安全檔名:UUID + 副檔名
$ext = match ($mime) {
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
default => 'bin',
};
$newName = bin2hex(random_bytes(16)) . '.' . $ext;
$destPath = UPLOAD_DIR . $newName;
// 6. 確保目錄存在
if (!is_dir(UPLOAD_DIR)) {
mkdir(UPLOAD_DIR, 0755, true);
}
// 7. 移動檔案(防止競態條件)
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
$response['message'] = '檔案儲存失敗';
echo json_encode($response);
exit;
}
// 8. 可選:圖片處理(縮圖、壓縮、去除 EXIF)
// $img = imagecreatefromstring(file_get_contents($destPath));
// ... 處理後覆蓋儲存
// 9. 回傳成功
$response['success'] = true;
$response['message'] = '上傳成功';
$response['data'] = [
'filename' => $newName,
'url' => '/storage/uploads/' . $newName,
'size' => $file['size'],
'mime' => $mime,
];
echo json_encode($response);
$_FILES['type'])php_flag engine off 或 Nginx location ~ \.php$ { deny all; } 禁止腳本執行<?php
$to = 'user@example.com';
$subject = '您的驗證碼';
$message = '您的驗證碼是:123456,10 分鐘內有效。';
$headers = "From: no-reply@mysite.com\r\n" .
"Reply-To: support@mysite.com\r\n" .
"Content-Type: text/plain; charset=UTF-8\r\n" .
"X-Mailer: PHP/" . phpversion();
if (mail($to, $subject, $message, $headers)) {
echo '發送成功';
} else {
error_log('郵件發送失敗:' . error_get_last()['message']);
}
<?php
// composer require symfony/mailer
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mime\Email;
require_once 'vendor/autoload.php';
$dsn = 'smtp://user:pass@smtp.example.com:587'; // 或 sendmail://default
$transport = Transport::fromDsn($dsn);
$mailer = new Mailer($transport);
$email = (new Email())
->from('no-reply@mysite.com')
->to('user@example.com')
->subject('您的驗證碼')
->text('您的驗證碼是:123456,10 分鐘內有效。')
->html('<p>您的驗證碼是:<strong>123456</strong>,<em>10 分鐘內有效</em>.</p>');
try {
$mailer->send($email);
echo '發送成功';
} catch (TransportExceptionInterface $e) {
error_log('郵件發送失敗:' . $e->getMessage());
}
掌握 Include 模板隔離敏感資料、半動態頁面緩解高併發、安全檔案上傳流程、現代郵件發送架構,是 PHP 開發者從「會寫網頁」邁向「建構健壯應用」的關鍵里程碑。