• Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Building a Simple WordPress Post List Tool with PHP

    Building a Simple WordPress Post List Tool with PHP

    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

    Building a Network Tracker Auditor for Privacy with Python

    Building a Network Tracker Auditor for Privacy with Python

    Streaming Audio Files Securely with PHP

    Streaming Audio Files Securely with PHP

    Scraping Web Data with Python Helium

    Scraping Web Data with Python Helium

    Building a Secure 2FA Authenticator with Python

    Building a Secure 2FA Authenticator with Python

    Building a Cache Warmer with Python

    Building a Cache Warmer with Python

    How to Create a Python GUI to Launch Webhooks

    How to Create a Python GUI to Launch Webhooks

  • Blog
    • All
    • Artificial Intelligence
    • Privacy
    • Reviews
    • Security
    • Tutorials
    Why Stable Websites Outperform Flashy Redesigns

    Why Stable Websites Outperform Flashy Redesigns

    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

    38 essential points to harden WordPress

    38 Essential Points to Harden WordPress

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Administration & Cybersecurity
No Result
View All Result
  • Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Building a Simple WordPress Post List Tool with PHP

    Building a Simple WordPress Post List Tool with PHP

    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

    Building a Network Tracker Auditor for Privacy with Python

    Building a Network Tracker Auditor for Privacy with Python

    Streaming Audio Files Securely with PHP

    Streaming Audio Files Securely with PHP

    Scraping Web Data with Python Helium

    Scraping Web Data with Python Helium

    Building a Secure 2FA Authenticator with Python

    Building a Secure 2FA Authenticator with Python

    Building a Cache Warmer with Python

    Building a Cache Warmer with Python

    How to Create a Python GUI to Launch Webhooks

    How to Create a Python GUI to Launch Webhooks

  • Blog
    • All
    • Artificial Intelligence
    • Privacy
    • Reviews
    • Security
    • Tutorials
    Why Stable Websites Outperform Flashy Redesigns

    Why Stable Websites Outperform Flashy Redesigns

    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

    38 essential points to harden WordPress

    38 Essential Points to Harden WordPress

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Administration & Cybersecurity
No Result
View All Result
Home Guides Programming PHP

Automating JavaScript Minification with PHP

Jonathan Moore by Jonathan Moore
2 years ago
Reading Time: 7 mins read
A A
Automating JavaScript Minification with PHP
FacebookTwitter

Automating JavaScript minification with PHP can significantly streamline a developer’s workflow. It ensures that the deployed code is always in its most optimized form without requiring manual intervention every time a change is made. The provided PHP code snippet exemplifies an automated solution for JavaScript minification. By utilizing an external minification service, the code performs the tedious task of compressing JavaScript files, making them more efficient for web delivery.

The Importance of Minification

Minification in web development stems from its ability to remove all unnecessary characters from code without changing its functionality. This process serves several critical purposes.

Minification speeds up the loading time of web pages. By compressing JavaScript files, making them smaller, they are downloaded more quickly, leading to faster page loads. This enhancement to the user experience can positively impact search engine rankings, as many search engines consider page load time as a factor in their algorithms.

Minification also reduces the amount of bandwidth used. The reduction in file size means less data is transferred between the server and the client, benefiting both hosting providers and users, especially those with limited or metered internet connections. This efficiency translates to cost savings and more efficient data usage.

The automation of minification can significantly streamline the development workflow. Developers can continue to work with well-formatted, readable code during the development stage, while the deployed code can be in its most optimized form. This way, developers are not burdened with manually minifying the code every time a change is made.

Minification is not merely a recommendation but a standard practice in modern web development. It helps make websites faster, more efficient, and more economical, all while easing the development process. Integrating minification into the development workflow, as shown in the example of automating JavaScript minification with PHP, allows developers to focus on creating fantastic web content without worrying about manual optimization tasks.

Creating a Function to Minify JavaScript

The foundation of our automation is a PHP function dedicated to minifying JavaScript files.

function update_minified_js( $js_file ) {
    // Define the URL for the minification service
    $api_url = 'https://www.toptal.com/developers/javascript-minifier/api/raw';

    // Check if the file exists and is readable
    if ( !file_exists( $js_file ) || !is_readable( $js_file ) ) {
        return false; // Exit if file does not exist or is not readable
    }

    // Get the contents of the JavaScript file
    $js = file_get_contents( $js_file );

    // Initialize cURL session
    $ch = curl_init();

    // Set cURL options for the POST request to the minification service
    curl_setopt_array( $ch, [
        CURLOPT_URL            => $api_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => ["Content-Type: application/x-www-form-urlencoded"],
        CURLOPT_POSTFIELDS     => http_build_query( [ "input" => $js ] )
    ] );

    // Execute the cURL request
    $minified = curl_exec( $ch );

    // Check for errors in the cURL request
    if ( curl_errno( $ch ) ) {
        curl_close( $ch );
        return false; // Exit if there's an error with the cURL request
    }

    // Close the cURL session
    curl_close( $ch );

    // Replace multiple whitespace characters with a single space
    $minified = preg_replace( '!\s+!', ' ', $minified );

    // Create the minified file's name
    $js_min_file = str_replace( ".js", ".min.js", $js_file );

    // Open the minified file for writing
    $fp = fopen( $js_min_file, 'w' );

    // Check if the file was opened successfully
    if ( !$fp ) {
        return false; // Exit if the file cannot be opened for writing
    }

    // Write the minified JavaScript to the file
    fwrite( $fp, $minified );

    // Close the file
    fclose( $fp );

    // Return success
    return true;
}

This code initiates by defining the URL for a minification service. Then, the function verifies whether the specified JavaScript file is accessible. It reads the file, initializes a cURL session, and sends the JavaScript code to the minification service through a POST request. The minified code is then retrieved, further compacted by removing additional whitespace, and written to a new file with a “.min.js” extension.

The detailed structure of this function ensures robustness. With provisions for error handling and considerations for various scenarios, it doesn’t merely send the file for minification but also manages potential issues.

With the function defined, the next step is to utilize it.

// Path to the source JS file
$js_file = 'js/source_file.js';

// Path to the minified JS file
$js_min_file = str_replace( ".js", ".min.js", $js_file );

// Check if the minified JS file exists
if ( !file_exists( $js_min_file ) ) {
    // If the minified JS file doesn't exist, call the function to create it
    update_minified_js( $js_file );
} else {
    // If the minified JS file does exist, compare the modification times
    $sourceFileTime   = filemtime( $js_file );
    $minifiedFileTime = filemtime( $js_min_file );

    // If the source JS file is newer than the minified file, call the function to update it
    if ( $sourceFileTime > $minifiedFileTime ) {
        update_minified_js( $js_file );
    }
}

This part checks for the minified JavaScript file and compares the original and minified files’ modification times. If the file doesn’t exist or if the original is newer, the function is called to create or update the minified file.

The ability to detect and act upon modifications in the original file ensures that manual intervention is not needed every time the original file is changed. This automation saves time and minimizes the risk of errors.

Example Usage: Integrating the Code into an HTML Document

Let’s look at how you might integrate this PHP code into a real-life scenario. For this example, we are going to create four separate files, a PHP file called minify.php, an HTML document named example.php, a JavaScript file called timezones.js, and a CSS file named style.css.

The following example usage is designed to use a directory structure like this one:

Root/<br>
├── js/<br>
│   └── timezones.js<br>
├── css/<br>
│   └── style.css<br>
├── example.php<br>
└── minify.php

Once you have your directory structure created, you can begin to create your files.

function update_minified_js( $js_file ) {
    // Define the URL for the minification service
    $api_url = 'https://www.toptal.com/developers/javascript-minifier/api/raw';

    // Check if the file exists and is readable
    if ( !file_exists( $js_file ) || !is_readable( $js_file ) ) {
        return false; // Exit if file does not exist or is not readable
    }

    // Get the contents of the JavaScript file
    $js = file_get_contents( $js_file );

    // Initialize cURL session
    $ch = curl_init();

    // Set cURL options for the POST request to the minification service
    curl_setopt_array( $ch, [
        CURLOPT_URL            => $api_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => ["Content-Type: application/x-www-form-urlencoded"],
        CURLOPT_POSTFIELDS     => http_build_query( [ "input" => $js ] )
    ] );

    // Execute the cURL request
    $minified = curl_exec( $ch );

    // Check for errors in the cURL request
    if ( curl_errno( $ch ) ) {
        curl_close( $ch );
        return false; // Exit if there's an error with the cURL request
    }

    // Close the cURL session
    curl_close( $ch );

    // Replace multiple whitespace characters with a single space
    $minified = preg_replace( '!\s+!', ' ', $minified );

    // Create the minified file's name
    $js_min_file = str_replace( ".js", ".min.js", $js_file );

    // Open the minified file for writing
    $fp = fopen( $js_min_file, 'w' );

    // Check if the file was opened successfully
    if ( !$fp ) {
        return false; // Exit if the file cannot be opened for writing
    }

    // Write the minified JavaScript to the file
    fwrite( $fp, $minified );

    // Close the file
    fclose( $fp );

    // Return success
    return true;
}
<?php
// Include the file containing the minification function
include 'minify.php';

// Path to the source JS file
$js_file = 'js/timezones.js';

// Path to the minified JS file
$js_min_file = str_replace( ".js", ".min.js", $js_file );

// Check if the minified JS file exists
if ( !file_exists( $js_min_file ) ) {
    // If the minified JS file doesn't exist, call the function to create it
    update_minified_js( $js_file );
} else {
    // If the minified JS file does exist, compare the modification times
    $sourceFileTime   = filemtime( $js_file );
    $minifiedFileTime = filemtime( $js_min_file );

    // If the source JS file is newer than the minified file, call the function to update it
    if ( $sourceFileTime > $minifiedFileTime ) {
        update_minified_js( $js_file );
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/style.css">
    <title>Display Times Zones Example</title>
</head>
<body>

    <div id="timeZoneDisplay"></div>

    <script src="<?php echo $js_min_file; ?>"></script>

</body>
</html>
function displayTimeZones() {
    // Define an array of time zones
    var timeZones = [
        'America/New_York',    // Eastern Standard Time
        'America/Chicago',     // Central Standard Time
        'America/Denver',      // Mountain Standard Time
        'America/Los_Angeles', // Pacific Standard Time
        'Pacific/Honolulu',    // Hawaii-Aleutian Standard Time
        'America/Anchorage'    // Alaska Standard Time
    ];

    // Start the table with a header row
    var tableString = "<table border='1'><tr><th>Time Zone</th><th>Current Time</th></tr>";

    // Iterate through the time zones and get the time for each
    for (var i = 0; i < timeZones.length; i++) {
        var timeZone = timeZones[i];

        // Get the current time for this time zone
        var timeZoneTime = new Date().toLocaleTimeString('en-US', { timeZone: timeZone });

        // Append the time zone name and time to the table
        tableString += "<tr><td>" + timeZone + "</td><td>" + timeZoneTime + "</td></tr>";
    }

    // Close the table
    tableString += "</table>";

    // Display the table on the webpage
    document.getElementById('timeZoneDisplay').innerHTML = tableString;
}

// Call the function to display the time zones
displayTimeZones();

// Update the time every second
setInterval(displayTimeZones, 1000);
#timeZoneDisplay {
    font-family: Arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
    max-width: 800px;
    margin: 20px auto;
}

#timeZoneDisplay table {
    border-collapse: collapse;
    width: 100%;
}

#timeZoneDisplay th, #timeZoneDisplay td {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

#timeZoneDisplay tr:nth-child(even) {
    background-color: #f2f2f2;
}

#timeZoneDisplay th {
    background-color: #4CAF50;
    color: white;
}

This example fully integrates the minification process into a typical HTML document. The code includes the minification function, checks if the minified file exists, compares file modification times, and either creates or updates the minified file as needed. The result is a self-sustaining system that ensures your website always uses the latest, optimized version of your JavaScript file.

Here is what the new timezones.min.js file would look like:

function displayTimeZones(){for(var e=["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Pacific/Honolulu","America/Anchorage"],i="<table border='1'><tr><th>Time Zone</th><th>Current Time</th></tr>",t=0;t<e.length;t++){var r=e[t],n=new Date().toLocaleTimeString("en-US",{timeZone:r});i+="<tr><td>"+r+"</td><td>"+n+"</td></tr>"}i+="</table>",document.getElementById("timeZoneDisplay").innerHTML=i}displayTimeZones(),setInterval(displayTimeZones,1e3);

By applying this technique, you can enhance your website’s loading speed and overall performance without manual intervention. It’s a practical and efficient way to maintain optimized JavaScript files, contributing to a more responsive user experience. The results for the JS files mentioned above went from 1.3 kB for timezones.js to 476 bytes for timezones.min.js. That is a huge saving!

Conclusion

Automating JavaScript minification with PHP is not just a coding technique; it’s a valuable strategy to enhance user experience and stay competitive in today’s online landscape. By understanding and implementing the code provided, you can ensure that your site remains optimized, responsive, and aligned with modern best practices.

Whether you are a seasoned developer or just starting, this automation will streamline your workflow, making your website agile and user-friendly. It’s a simple yet powerful step towards achieving higher efficiency and performance.

Tags: JavaScriptMinificationPHP
ShareTweetSharePinShareShareScan
ADVERTISEMENT
Jonathan Moore

Jonathan Moore

Senior Software Engineer and Cybersecurity Specialist with over 3 decades of experience in developing web, desktop, and server applications for Linux and Windows-based operating systems. Worked on numerous projects, including automation, artificial intelligence, data analysis, application programming interfaces, intrusion detection systems, streaming audio servers, WordPress plugins, and much more.

Related Articles

Building a Simple WordPress Post List Tool with PHP

Building a Simple WordPress Post List Tool with PHP

I needed a quick way to view all my WordPress posts without logging into the admin dashboard. Sometimes you just...

Streaming Audio Files Securely with PHP

Streaming Audio Files Securely with PHP

PHP is widely used for managing file access, handling data securely, and serving multimedia content online. One of the common...

Calculating the Date of Easter Using the Computus Algorithm

Calculating the Date of Easter Using the Computus Algorithm

Easter is one of the oldest and most significant festivals in the Christian calendar, celebrating the resurrection of Jesus Christ....

Next Post
Privacy-Focused Analytics

Privacy-Focused Analytics: Balancing Insights and Integrity

Recommended Services

Latest Articles

Building a Simple WordPress Post List Tool with PHP

Building a Simple WordPress Post List Tool with PHP

I needed a quick way to view all my WordPress posts without logging into the admin dashboard. Sometimes you just...

Read moreDetails

Why Stable Websites Outperform Flashy Redesigns

Why Stable Websites Outperform Flashy Redesigns

Most websites do not fail in dramatic fashion. There is no explosion, no warning siren, no obvious moment where everything...

Read moreDetails

Monitoring Web Page Changes with Python

Monitoring Web Page Changes with Python

There are times when I need to know that a web page has changed without actively watching it. That might...

Read moreDetails

My SSH Setup: How I Manage Multiple Servers

My SSH Setup: How I Manage Multiple Servers

If you work with more than one server, the need to manage multiple servers with SSH becomes obvious pretty quickly....

Read moreDetails
  • Privacy Policy
  • Terms of Service

© 2025 JMooreWV. All rights reserved.

No Result
View All Result
  • Home
  • Guides
    • Linux
    • Programming
      • JavaScript
      • PHP
      • Python
    • Tools
    • WordPress
  • Blog
    • Artificial Intelligence
    • Tutorials
    • Privacy
    • Security
  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Administration & Cybersecurity