萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 進階技巧:Include 模板、半動態頁面、檔案上傳與 Email 發送實戰

PHP 內建函式庫的威力

PHP 擁有龐大的內建函式庫,涵蓋資料庫、檔案系統、網路、圖像、加密、壓縮等領域,讓開發者無需安裝額外擴充即可完成複雜任務。本文深入四大進階主題:模板系統、效能優化、檔案上傳、郵件發送。

一、伺服器端包含:打造可維護的模板系統

基本用法

<!-- include/header.php -->
<header>
    <h1></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、查詢資料庫、渲染模板。對高流量頁面(首頁、列表頁),可採用「定期靜態化」策略:

實作原理

  1. 後台腳本 generate_homepage.php 執行完整邏輯,輸出 HTML 存為 cache/index.html。
  2. 前端 Web 伺服器(Nginx/Apache)直接服務靜態 index.html,完全繞過 PHP。
  3. 排程(Cron / Systemd Timer)每 5-15 分鐘重新產生,或資料變更時觸發重建。

簡易產生腳本範例

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

Nginx 設定優先服務快取

location / {
    try_files /cache/index.html $uri $uri/ /index.php?$query_string;
}

三、檔案上傳:安全、完整、可擴充的實作

HTML 表單必要條件

<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 端完整處理流程

<?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);

安全檢查清單

  • ✅ 驗證 MIME 型別(不要信任 $_FILES['type'])
  • ✅ 限制檔案大小(PHP.ini + 程式碼雙重保險)
  • ✅ 重新命名檔案,防止路徑遍歷、覆蓋、執行惡意腳本
  • ✅ 上傳目錄設定 php_flag engine off 或 Nginx location ~ \.php$ { deny all; } 禁止腳本執行
  • ✅ 病毒掃描(ClamAV)針對高風險業務

四、Email 發送:從 mail() 到現代郵件庫

原生 mail() 簡易範例(不推薦生產環境)

<?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']);
}

為什麼不推薦 mail()?

  • 依賴本機 MTA(Sendmail/Postfix),配置複雜、易進垃圾郵件
  • 無 SMTP 認證、TLS 加密、DKIM/SPF 簽名支援
  • 難以處理 HTML 郵件、附件、內嵌圖片
  • 無發送佇列、重試、退信處理機制

現代解決方案:Symfony Mailer / PHPMailer

<?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());
}

生產環境加分項

  • 使用專業郵件服務:SendGrid、Mailgun、Amazon SES、Postmark(高送達率、統計分析、退信處理)
  • 實作佇列發送:Laravel Queue、Symfony Messenger、RabbitMQ/Redis,避免阻塞 HTTP 請求
  • 模板系統:Twig 檔案分離 HTML/純文字版本,支援多語系
  • 追蹤像素/連結點擊統計:自訂追蹤 ID 記錄開信率、點擊率

總結

掌握 Include 模板隔離敏感資料、半動態頁面緩解高併發、安全檔案上傳流程、現代郵件發送架構,是 PHP 開發者從「會寫網頁」邁向「建構健壯應用」的關鍵里程碑。

copyright © 萬盛學電腦網 all rights reserved