Combine JS or CSS files with PHP

Combining Javascript and CSS files and can tremendously reduce the number of HTTP requests your page make, making your website lighter and faster. It’s one of those tweaks to improve your website performance. This snippet doesn’t minify files, it just simply combines multiple files into single one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function combine_my_files($array_files, $destination_dir, $dest_file_name){

    if(!is_file($destination_dir . $dest_file_name)){ //continue only if file doesn't exist
        $content = "";
        foreach ($array_files as $file){ //loop through array list
            $content .= file_get_contents($file); //read each file
        }

        //You can use some sort of minifier here
        //minify_my_js($content);

        $new_file = fopen($destination_dir . $dest_file_name, "w" ); //open file for writing
        fwrite($new_file , $content); //write to destination
        fclose($new_file);
        return '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combined file
    }else{
        //use stored file
        return '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combine file
    }
}

Usage

Just make a list of files you want to combine, and then call the function to do the rest. Make sure destination path is writable and correct.

1
2
3
4
5
6
7
8
9
$files = array(
            'http://example/files/sample_js_file_1.js',
            'http://example/files/sample_js_file_2.js',
            'http://example/files/beautyquote_functions.js',
            'http://example/files/crop.js',
            'http://example/files/jquery.autosize.min.js',
            );
           
echo combine_my_files($files, 'minified_files/', md5("my_mini_file").".js");

This is a simple approach, but there are already many powerful PHP scripts and libraries such as this one or this, which can easily combine and minify your Javascript and CSS files.