SoFunction
Updated on 2025-03-02

Detailed explanation of PHP merge static files

Configuration

Change the configuration item (must) auto_prepend_file = "C:\xampp\htdocs\auto_prepend_file.php"

Change configuration item (optional) allow_url_include = On

auto_prepend_file.php file content

Copy the codeThe code is as follows:

<?php
/**
* Introduce static files
* @param {array|string} Relative path
* @param {string} The path where the script is currently executed is__FILE__
 *
 */
function import_static($files, $path=NULL){
// Change the execution path of the current script
    $old_dir = getcwd();
    $tmp_dir = (isset($path)) ? dirname($path): dirname(__FILE__);
    chdir($tmp_dir);
// Organize the included files
    if (!is_array($files)) {
        $tmp = array();
        $tmp[] = $files;
        $files = $tmp;
    }
// Send header information
    if (isset($files[0])) {
        if (stripos($files[0], '.js') !== false) {
            $header_str = 'Content-Type:   text/javascript';
        } elseif (stripos($files[0], '.css') !== false) {
            $header_str = 'Content-Type:   text/css';
        }
        if (!ob_get_contents()) {
            header($header_str);
        }
    }
//Introduce included files
    foreach($files as $key=>$value) {
        require_once($value);
    }
// Change back to the execution path of the current script
    chdir($old_dir);
}
?>

How to use

Copy the codeThe code is as follows:

"", "" and "../" are the JS files to be merged. If you merge them into, the code in them is as follows:
<?php
    import_static(array(
        '',
        '',
        '../',
'../moduleB/'    // You can also reference .php files
    ), __FILE__);
?>

Use <script type="text/javascript" src=""></script> to introduce it in HTML pages.

Before the product is launched, it uses batch files for processing, mainly doing two aspects of work.
1. Export "*." to the "*.js" file and delete "*." Command line: php *. &gt *.js
2. Replace the reference to "*." in the HTML page with "*.js". preg_replace()

PS: The import_static function solves the problem of include() handling relative paths in PHP.

The above is the entire content of this article. For more detailed information, please look forward to subsequent articles.