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

PHP 靜態資源合併載入:auto_prepend_file 實戰指南

     編輯:PHP 綜合知識

核心思路

利用 PHP 的 auto_prepend_file 機制,在每個腳本執行前自動載入合併邏輯,實現多個 JS/CSS 檔案的動態合併輸出,上線前再透過批次處理生成靜態檔案,兼顧開發便利與生產效能。

配置步驟

1. 修改 php.ini

; 必須項
auto_prepend_file = "C:\xampp\htdocs\auto_prepend_file.php"

; 可選,允許包含遠端 URL
allow_url_include = On

2. 核心合併函數 auto_prepend_file.php

<?php
/**
 * 引入並合併靜態資源檔案
 * @param array|string $files 相對路徑陣列或單一路徑
 * @param string $path 當前執行腳本路徑 (__FILE__)
 */
function import_static($files, $path = null)
{
    // 保存並切換工作目錄,解決相對路徑問題
    $oldDir = getcwd();
    $baseDir = $path ? dirname($path) : dirname(__FILE__);
    chdir($baseDir);

    // 統一轉為陣列
    if (!is_array($files)) {
        $files = [$files];
    }

    // 根據第一個檔案副檔名自動發送 Content-Type
    if (isset($files[0]) && !ob_get_contents()) {
        if (stripos($files[0], '.js') !== false) {
            header('Content-Type: text/javascript');
        } elseif (stripos($files[0], '.css') !== false) {
            header('Content-Type: text/css');
        }
    }

    // 依序引入檔案
    foreach ($files as $file) {
        require_once $file;
    }

    // 還原工作目錄
    chdir($oldDir);
}

使用範例

建立合併入口檔 base.js.php

<?php
import_static([
    'a.js',
    'b.js',
    '../c.js',
    '../moduleB/all.js.php'  // 也可引用其他 PHP 合併檔
], __FILE__);

HTML 中引用

<script type="text/javascript" src="base.js.php"></script>

生產環境部署:批次生成靜態檔

上線前執行以下兩步,將動態合併轉為靜態檔案:

  1. 生成靜態檔:php *.js.php > *.js(並刪除 *.js.php)
  2. 替換 HTML 引用:使用 preg_replace() 將 *.js.php 替換為 *.js

關鍵優勢

  • 開發階段:修改子檔案即時生效,無需手動合併
  • 生產階段:靜態檔案直接由 Web Server 服務,零 PHP 開銷
  • 解決 include() 相對路徑失效的痛點

注意事項

  • 確保合併檔案編碼一致(建議 UTF-8 且無 BOM)
  • 避免在合併檔中輸出多餘空白字元
  • 生產環境務必關閉 auto_prepend_file,改用靜態檔
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved