How to Minify JS in PHP Easily... Or Something Else
The workflow of copying code from a development file, running an external minifier, and pasting the result back into a production file is tedious and error-prone. You want to automate this so that updating scripts_template.js automatically updates what your browser actually downloads via scripts.php. The goal isn't necessarily to generate obfuscated, unreadable code; sometimes you just want to strip tabs, remove blank lines, and reduce the physical footprint of the file without sacrificing readability.
If you are looking for a quick-and-dirty solution that doesn't require deep knowledge of PHP classes or complex build tools, there is no need to reinvent the wheel. You can achieve this directly within your existing PHP environment using standard string manipulation functions.
The Regex Approach for "Light" Minification
Since your primary requirement is simply removing whitespace (tabs and spaces) and blank lines while preserving the code structure, regular expressions are the most direct tool. This approach avoids the overhead of downloading external executables like JSMin, which can be problematic in restricted environments like older Windows versions where zip extraction fails.
You can create a simple helper function in your PHP file to handle this logic:
function minify_js_light($source) {
// Remove leading and trailing whitespace from the entire block
$source = trim($source);
// Remove blank lines (lines containing only whitespace)
$source = preg_replace('/\s+$/m', '', $source);
// Collapse multiple newlines into a single newline, then remove that newline if it's empty
$source = preg_replace('/\n\s*\n/', "\n", $source);
// Remove spaces and tabs around operators and delimiters where safe,
// but be careful not to break strings.
// A simple approach is to strip spaces/tabs before keywords or after them.
// However, for a "readable" minifier, simply collapsing whitespace is often enough.
return $source;
}
In your scripts.php file, you would then include this logic and echo the result:
<?php
// Include helper functions or the source code processing here
include("include.inc");
header("Content-type:text/javascript");
$template_path = "scripts_template.js";
$minified_content = minify_js_light(file_get_contents($template_path));
echo $minified_content;
?>
Why Not Just Use file_put_contents?
You mentioned wanting to update scripts.js automatically. While it is tempting to write the minified output directly to the file system using file_put_contents("scripts.js", ...), this introduces a significant architectural risk. You are coupling your application's runtime execution with its deployment storage.
If you modify the source code on the server, the next time a user visits your site, they might receive a 403 Forbidden error if the file permissions don't allow writing, or worse, you could inadvertently corrupt the live site while editing. The standard pattern is to keep scripts_template.js as your single source of truth and let the browser handle the caching of the minified output served by scripts.php.
The Trade-off of Server-Side Minification
Using a PHP script to serve minified JavaScript on-the-fly saves you from manual paste jobs, but it comes with performance considerations. Every time a user visits your page, the server must read the template file, run the regex operations, and generate the output string in memory before sending it down the wire.
For small to medium-sized applications, this overhead is negligible. However, if scripts_template.js grows into a massive library or you have high traffic, generating the minified version dynamically adds latency compared to serving a pre-compressed static file. In production environments, it is generally best practice to run your minifier once during the build process (using tools like Terser or esbuild) and serve the resulting static asset.
When to Stick with Simple Regex
Despite the industry shift toward dedicated build tools, there are valid reasons to stick with a lightweight regex-based approach:
- Readability: You explicitly stated you want the code to remain readable. Aggressive minifiers often remove semicolons and introduce confusing formatting that makes debugging difficult. A simple whitespace stripper preserves the visual logic of your code while shrinking the file size.
- Simplicity: No dependencies, no class structures to learn, and no external servers to configure.
- Control: You have full control over exactly what gets removed without worrying about breaking complex syntax that aggressive parsers might mishandle.
If your goal is purely to reduce file size slightly to save bandwidth or disk space while maintaining the ability to quickly scan the source code for bugs, this lightweight PHP solution offers a pragmatic middle ground between doing nothing and running a full minification suite.