Combine JS or CSS files with PHP

Any good developer can explain the effect of combining Javascript and CSS files. It simply reduces the number of HTTP requests your page make, making your website lighter and faster. It’s one of the many tweaks to improve your website performance. This snippet doesn’t minify files but it will combine 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.

    Message Type : Question Comment ?
    • Question : Can include code, jsFiddle, codePen etc using Markdown Syntax.
    • Comment : Short comments and questions.