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

PHP 依 URL 自動產生縮圖:Apache Rewrite + 動態處理機制

     編輯:PHP 相關知識

PHP 依 URL 自動產生縮圖實作

傳統縮圖需預先批次處理。本文實作「依請求動態產生」機制:當縮圖不存在時,透過 Apache Rewrite 導向 PHP 腳本即時生成並輸出,後續請求直接由 Web Server 靜態服務。

架構設計

原圖:  https://example.com/upload/news/2013/07/21/1.jpg
縮圖:  https://example.com/supload/news/2013/07/21/1.jpg
       ↑ 若不存在 → Rewrite → createthumb.php?path=/supload/news/... → 產生 → 輸出

目錄結構

www/
├── PicThumb.class.php      # 縮圖核心類
├── ThumbConfig.php         # 縮圖規則設定
├── upload/                 # 原圖根目錄
│   └── news/2013/07/21/1.jpg
└── supload/                # 縮圖根目錄 (對外公開)
    ├── .htaccess           # Rewrite 規則
    ├── watermark.png
    └── createthumb.php     # 動態產生入口

.htaccess Rewrite 規則

<IfModule mod_rewrite.c>
RewriteEngine On
# 靜態檔案直接服務
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
# 其餘導向 PHP 處理
RewriteRule ^.*$ createthumb.php?path=%{REQUEST_URI} [NC,L]
</IfModule>

createthumb.php 核心邏輯

<?php
define('WWW_PATH', dirname(dirname(__FILE__)));
require(WWW_PATH . '/PicThumb.class.php');
require(WWW_PATH . '/ThumbConfig.php');

$logfile = WWW_PATH . '/createthumb.log';
$source_path = WWW_PATH . '/upload/';
$dest_path = WWW_PATH . '/supload/';

$path = isset($_GET['path']) ? $_GET['path'] : '';
if (!$path) exit();

// 解析請求路徑對應的規則
$relative_url = str_replace($dest_path, '', WWW_PATH . $path);
$type = substr($relative_url, 0, strpos($relative_url, '/'));
$config = isset($thumb_config[$type]) ? $thumb_config[$type] : '';
if (!$config || !isset($config['fromdir'])) exit();

// 來源/目標檔案路徑
$source = str_replace('/' . $type . '/', '/' . $config['fromdir'] . '/', $source_path . $relative_url);
$dest = $dest_path . $relative_url;

// 產生縮圖
$obj = new PicThumb($logfile);
$obj->set_config($config);
if ($obj->create_thumb($source, $dest)) {
    ob_clean();
    header('Content-Type: ' . mime_content_type($dest));
    exit(file_get_contents($dest));
}
?>

ThumbConfig.php 規則設定

<?php
$thumb_config = array(
    'news' => array(
        'fromdir' => 'news',
        'type' => 'fit',
        'width' => 100,
        'height' => 100,
        'bgcolor' => '#FF0000'
    ),
    'news_1' => array(
        'fromdir' => 'news',
        'type' => 'fit',
        'width' => 200,
        'height' => 200,
        'bgcolor' => '#FFFF00'
    ),
    'article' => array(
        'fromdir' => 'article',
        'type' => 'crop',
        'width' => 250,
        'height' => 250,
        'watermark' => WWW_PATH . '/supload/watermark.png'
    )
);

運作流程

  1. 請求 /supload/news/2013/07/21/1.jpg
  2. 檔案不存在 → Rewrite 導向 createthumb.php?path=/supload/news/...
  3. 解析 type=news,載入對應設定
  4. 對應原圖 /upload/news/2013/07/21/1.jpg
  5. 呼叫 PicThumb 產生縮圖儲存至 /supload/news/...
  6. 直接輸出圖片內容
  7. 下次請求同一 URL,Apache 直接服務靜態檔案,不經 PHP

優點

  • 零預處理:上傳原圖即可,縮圖按需產生
  • 彈性規則:同一原圖可產生多種尺寸/風格(如 news、news_1)
  • 效能最佳:產生後轉為靜態檔案,無 PHP 開銷
  • 快取友善:可搭配 CDN、瀏覽器快取

注意事項

  • 確保 supload 目錄可寫入
  • 生產環境建議加入鎖機制避免並發重複產生
  • 定期清理舊縮圖或設定自動過期
  • 錯誤處理:原圖不存在時回傳 404 或預設佔位圖
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved