Explanation of PHP Merging Static Files

  • 2021-07-26 07:20:35
  • OfStack

Configuring PHP. ini

Change configuration entry (required) auto_prepend_file = "C:\ xampp\ htdocs\ auto_prepend_file. php"

Change configuration entry (optional) allow_url_include = On

auto_prepend_file. php file contents


<?php
/**
 * Introduce static Documents
 * @param {array|string} Relative path
 * @param {string} The path where the script is currently executing __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 include 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);
        }
    }
    // Introducing an include file
    foreach($files as $key=>$value) {
        require_once($value);
    }
    // Change back to the execution path of the current script
    chdir($old_dir);
}
?>

Usage


"a.js" , "b.js" And "../c.js" Is to be merged JS File, merge it into a base.js.php , then base.js.php The code in:
<?php
    import_static(array(
        'a.js',
        'b.js',
        '../c.js',
        '../moduleB/all.js.php'    // Can also be referenced .php Documents
    ), __FILE__);
?>

Use in the HTML page < script type="text/javascript" src="base.js.php" > < /script > Can be introduced.

Before the product goes online, batch files are used for processing, which mainly does two aspects of work
1. Output "*. js. php" to the "*. js" file and delete "*. js. php". Command line: php *. js. php & gt *.js
2. Replace the reference to "*. js. php" on the HTML page with "*. js". preg_replace ()

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

This is the whole content of this article. Please look forward to the following articles for more detailed information


Related articles: