Skip to content

A simple PHP script example to combine and minify multiple JS or CSS files passed via URI

License

Notifications You must be signed in to change notification settings

dmhendricks/php-combine-scripts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Author License DigitalOcean Twitter

PHP Combine Scripts

A simple PHP script to combine and minify multiple JS or CSS files passed via URI, inspired by jsDelivr.

It was created for when you have multiple scripts at a static/CDN domain, allowing you to pick and bundle different libraries based on your current needs.

Generally, it is best to combine multiple assets into bundles using a task runner such as webpack or Gulp, but it can be handy depending on your use case.

Setup

  1. Clone or unzip the files to a directory off of your web root. For example, /combine/. Change to that directory.
  2. composer install
  3. Rename .env-sample to .env. Set the COMBINE_BASEDIR to the directory that will contain your JS/CSS files that you want to allow combining/minification for.
  4. Configure your web server to rewrite URLs, as shown in the examples below. Change the /combine/ and /minify/ paths as desired.

Nginx

# Rewrite combine/minify URLs
rewrite ^/combine/(.*)$ /combine/index.php?scripts=$1;
rewrite ^/minify/(.*)$ /combine/index.php?minify=true&scripts=$1;

Apache

# Rewrite combine/minify URLs
RewriteRule "^/combine/(.*)$" "/combine/index.php?scripts=$1"
RewriteRule "^/minify/(.*)$" "/combine/index.php?minify=true&scripts=$1"

Usage Example

For example, let's say that you set your COMBINE_BASEDIR to /var/www/html/scipts/. Withing this directory, you might have some JS or CSS libraries. We'll combine Font Awesome with the v4 shims as an example, assuming that you have already extracted them to /var/www/html/scipts/dist/css/.

To combine or minify multiple scripts, separate them with commas:

<!-- Combine example -->
<link rel="stylesheet" href="https://example.com/combine/dist/css/all.min.css,dist/css/v4-shims.min.css" />

<!-- Minify example -->
<link rel="stylesheet" href="https://example.com/minify/dist/css/all.css,dist/css/v4-shims.css" />

Of course, minification is not necessary for scripts that you already have minified versions for. It is merely an option for libraries/scripts that do not contain a minified version. If you have minified versions avaible, it is recommended to simply use the "combine" method as it consumes less system resources.

About

A simple PHP script example to combine and minify multiple JS or CSS files passed via URI

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages