DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Inheritance in PHP: A Simple Guide With Examples
  • The Blue Elephant in the Room: Why PHP Should Not Be Ignored Now or Ever
  • Laravel for Beginners: An Overview of the PHP Framework
  • Is PHP Still the Best Language in 2024?

Trending

  • Stabilizing ETL Pipelines With Airflow, Presto, and Metadata Contracts
  • Server-Driven UI: Agile Interfaces Without App Releases
  • Serverless Machine Learning: Running AI Models Without Managing Infrastructure
  • Deploying LLMs Across Hybrid Cloud-Fog Topologies Using Progressive Model Pruning
  1. DZone
  2. Coding
  3. Languages
  4. PHP: How to Add Expire Headers for External Scripts

PHP: How to Add Expire Headers for External Scripts

In this post we tackle the issue of how to add expire headers to external scripts to help ensure your site keeps running fast without sacrificing any flexibility.

By 
Jean-Baptiste Jung user avatar
Jean-Baptiste Jung
·
Aug. 24, 17 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
21.1K Views

Join the DZone community and get the full member experience.

Join For Free

PHP: How to add expire headers for external scripts

Every website is using external JavaScript files. They are required, for example, when using Google Analytics, or an ad provider like BuySellAds. In order to leverage browser caching and optimize your website speed, it is recommended that you add expire headers to your script, which you can't do on external files. In this article, I'll show you how to dynamically import external JavaScript files into your own website for better performance.


The Problem With External Scripts

When using an external service as such as Google Analytics, you are often required to include external JavaScript files into your own website.

While this isn’t a problem per se, you obviously don’t have as much control over those files than over files hosted on your own server. This is especially problematic since you should always set an expire header to static files in order to leverage browser caching and optimize your website speed.

Google PageSpeed Insight will recommend you to do so:

Image title

The Solution: Adding Expire Headers to External Scripts

So what we need to do is to import all the .js files dynamically into our website. To do so, we’ll use PHP and the file_get_contents(). The first thing to do is to locate the external script:

<script type="text/javascript" src="https://ssl.google-analytics.com/ga.js"></script>
The next step is to create a .php file. Let’s call it externaljs.php. Insert the following code in it: Let’s have a look at the code:
<?php

$files = array(
	'ga.js' => 'https://ssl.google-analytics.com/ga.js',
	'bsa.js' => 'https://s3.buysellads.com/ac/bsa.js',
	'pro.js' => 'https://s3.buysellads.com/ac/pro.js'
);

if(isset($files[$_GET['file']])) {
	if ($files[$_GET['file']] == 'ga.js'){
		header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + ((60 * 60) * 48))); // 2 days for GA
	} else {
		header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60))); // Default set to 1 hour
	}

	echo file_get_contents($files[$_GET['file']]);
}

?>
  • Lines 3 to 7: An array containing the accepted files is created. This is super important since, otherwise, any file could be embedded into your site, leading to potential security problems.      
  • Lines 9 to 14: Since we need to adjust the expiring time for every script, we need a conditional statement to do so.
  • Line 16: If the script passed out as a GET parameter is found in our array, we can now safely display it.

You’ll need to adjust the code and enter the URLs of your external scripts. Once done, just upload it to your server. If you’re using WordPress, it’s a good idea to put the file in your theme folder.

Then, simply replace the external .js call and replace it with a call to your externaljs.php

<script type="text/javascript" src="externaljs.php?url=ga.js"></script>

And you’re done. You can now dynamically import external .js file on your server and, therefore, set the right expire header for each script.

PHP

Published at DZone with permission of Jean-Baptiste Jung, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Inheritance in PHP: A Simple Guide With Examples
  • The Blue Elephant in the Room: Why PHP Should Not Be Ignored Now or Ever
  • Laravel for Beginners: An Overview of the PHP Framework
  • Is PHP Still the Best Language in 2024?

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: