Advertisement
  1. Code
  2. PHP

3 Ways to Speed up Your Site with PHP

Scroll to top
Read Time: 18 min

These days, with broadband connections the norm, we don't need to worry as much about internet speeds or the filesize of our pages. However, that's not to say that we still shouldn't do so. If you wish to reduce the load times on your server, decrease the number of HTTP requests, and go that extra bit for your visitors, there are a few techniques that you can use. This tutorial covers a number of PHP tricks, including caching and compression.

1. CSS Amalgamation with PHP

As web developers, we often split up our CSS between several separate files to keep a logical separation and to make modifications easier. However, this increases the number of requests to the server, resulting in a slower page load. Using some PHP we can have the best of both worlds; keeping multiple files on our end, and using one request to retrieve all of them.

Preparation

Before we can optimize CSS files, we will need some CSS to work with! So let's make three files and put some CSS in them.

1
2
	// main.css
3
	// Just some sample CSS
4
	
5
	body {
6
		width: 800px;
7
		margin: 0 auto;
8
		color: grey;
9
	}
10
	
11
	#wrapper {
12
		margin-top: 30px;
13
		background: url(../images/cats.png);
14
	}
1
2
	// typography.css
3
	// Just some sample CSS
4
	
5
	body {
6
		font-family: Arial, san-serif;
7
		font-weight: bold;
8
	}
9
	
10
	strong {
11
		font-size: 120%;
12
	}
1
2
	// forms.css
3
	// Just some sample CSS
4
	
5
	form {
6
		position: relative;
7
		top: 400px;
8
		z-index: 99;
9
	}
10
	
11
	input {
12
		height: 50px;
13
		width: 400px;
14
	}

The PHP

We need to get the contents of these files and append them to each other in a specified order. So our script has to receive the names of the CSS files via URL parameters, open all the files and put them together. An explanation of the code follows.

1
2
<?php
3
//Lets define some useful variables
4
// --- NOTE: PATHS NEED TRAILING SLASH ---
5
$cssPath = './css/';
6
7
if (isset($_GET['q'])) {
8
	$files = $_GET['q'];
9
	// Got the array of files!
10
	
11
	//Lets just make sure that the files don't contain any nasty characters.
12
	foreach ($files as $key => $file) {
13
		$files[$key] = str_replace(array('/', '\\', '.'), '', $file);
14
	}
15
	
16
	$cssData = '';
17
	foreach ($files as $file) {
18
		$cssFileName = $cssPath . $file . '.css';
19
		$fileHandle = fopen($cssFileName, 'r');
20
		$cssData .= "\n" . fread($fileHandle, filesize($cssFileName));
21
		fclose($fileHandle);
22
	}
23
}
24
25
// Tell the browser that we have a CSS file and send the data.
26
header("Content-type: text/css");
27
if (isset($cssData)) {
28
	echo $cssData;
29
	echo "\n\n// Generated: " . date("r");
30
} else {
31
	echo "// Files not avalable or no files specified.";
32
}
33
?>

Breaking it Down

It looks quite complicated, but stick with me, it's really pretty simple.

1
2
<?php
3
//Lets define some usefull variables
4
// --- NOTE: PATHS NEED TRAILING SLASH ---
5
$cssPath = './css/';
6
7
if (isset($_GET['q'])) {
8
	$files = $_GET['q'];
9
	// Got the array of files!
10
	
11
	//Lets just make sure that the files don't contain any nasty charactors.
12
	foreach ($files as $key => $file) {
13
		$files[$key] = str_replace(array('/', '\\', '.'), '', $file);
14
	}

This chunk of code sets the path for the CSS folder and checks that we have been sent some files to work with. The CSS path needs to have trailing slashes otherwise we will find ourselves with bucket-loads of errors. If we wanted, we could check automatically for a slash and add it if required. However, for the sake of simplicity I omitted that behavior.

Next we check each filename and remove any full stops and/or slashes. This prevents people from navigating the filesystem by passing filenames such as '../../secret/file'.

1
2
	$cssData = '';
3
	foreach ($files as $file) {
4
		$cssFileName = $cssPath . $file . '.css';
5
		$fileHandle = fopen($cssFileName, 'r');
6
		$cssData .= "\n" . fread($fileHandle, filesize($cssFileName));
7
		fclose($fileHandle);
8
	}
9
}

Now we have to build our CSS data from the individual files. To do this, we loop through the files array with foreach, open each file and append the contents onto our data. The "\n" simply adds a new line character to keep things nice and tidy. The filesize() function is used to find the length of the file so that we can tell fread() how much we want (the entire file).

1
2
// Tell the browser that we have a CSS file and send the data.
3
header("Content-type: text/css");
4
if (isset($cssData)) {
5
	echo $cssData;
6
	echo "\n\n// Generated: " . date("r");
7
} else {
8
	echo "// Files not avalable or no files specified.";
9
}
10
?>

The last bit of the script is to send the CSS data to the browser. This means we have to tell PHP that we are sending CSS data, and that it should inform the browser. We do this with the header function, setting the content type to 'text/css'. Then we send the CSS to the client. We first check if there is any CSS data to send. If there isn't, then this means that no names of CSS files were sent. If this is the case we simply reply with a CSS comment saying so. If, however, we do have some data to send, then we send that and add a message detailing when it was generated. If you wanted to, for example, add some copyright information to all your CSS in one go, then this would be an ideal place.

Putting it to the Test

Okay, now it's time to test the script; we need to first build a directory structure and then place our script and CSS files. Have a look at the image below and try to replicate that structure. If you want something different, don't forget to change the paths to reflect those changes.

Once everything is in the right place, we can test our script. The directory structure will have to be placed in the 'htdocs' or 'www' folder of a webserver with PHP (pretty much any webserver these days). Navigate to the index.php file. You should be greeted by a single comment: 'Files not available or no files specified'. This means that we have not given any files for it to pull together. However, the good news is that this is a valid CSS comment and won't cause any problems.

Let's give something a little trickier a go; type in 'index.php?q[]=main', you should get the CSS from you main.css file and a notice at the bottom.

If we want to pull multiple files together (as this was really the entire point of the script) we can send this request: 'index.php?q[]=main&q[]=forms'. As you can see we can repeat 'q[]=' as many times as we want because it is adding each value to an array. You could potentially add 50 CSS files together if you wanted using this script.

Concluding

Using this method can be very useful, and can provide benefits such as being able to have a default style sheet for every page and and an extra CSS file for pages with forms. It's also easy to implement if you're already using some sort of CSS processing with PHP. If you want, you can even rename index.php to index.css as long as you set up .htaccess to treat CSS files as PHP.

You might notice that I'm treating different orders of CSS files as different. This is because you may wish to have one stylesheet override another and therefore the order of the files is important. If this isn't a problem for you, you may wish to perform a sorting function on the files array before processing.

Just a word of caution; if you place the index.php file in any folder other than the one that contains the CSS then you have to write your relative background image paths as if index.php was your stylesheet. This is because that's what the browser thinks it is. Alternatively, you could add some code to rewrite these URLs, however, that is beyond the scope of this tutorial.

2. Stripping Whitespace from your HTML and CSS

Many of us use large amounts of whitespace when writing code. The good news is that whitespace in PHP doesn't actually get sent to the browser. However, it does in HTML.

Browsers tend to only display one space no matter how many tabs you use in your code. This means that there is some wasted bandwidth. However, with some simple PHP we can remove this bandwidth leeching whitespace.

Preparation

Once again, we will need some raw data to work with; so copy the following example HTML and CSS code. Save the following into a .htm and a .css file in a folder within your server's webroot directory.

1
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3
	"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
<html>
5
	<head>
6
		<title>Hey a Page!</title>
7
		<link rel="stylesheet" href="./css.css" type="text/css">
8
	</head>
9
	<body id="homepage">
10
		<div id="wrapper">
11
			<div id="header">
12
				<h1>Kittens for sale!</h1>
13
				<div>
14
					There   are      lots      of spaces here! But we need to get    rid   of  them!
15
				</div>
16
			</div>
17
			<div id="mainbody">
18
				Lorem Ipsum dol...
19
			</div>
20
		</div>
21
	</body>
22
</html>
1
2
body {
3
	min-height: 800px;
4
	background: black;
5
	font-size: 18px;
6
}
7
8
#wrapper {
9
	width: 960px;
10
	margin: 20px auto;
11
	padding: 15px;
12
}
13
14
#header h1 {
15
	text-indent: -99999em;
16
	background: url(../images/header.png);
17
	display: block;
18
	width: 100%;
19
	height: 48px;
20
}
21
22
#mainbody {
23
	font-weight: bold;
24
}

The PHP

One of the advantages of this method is that the same script will work with both HTML and CSS. Our script has to accept a filename as part of the request. Once the file has been loaded, it has to strip all whitespace down to just one space character. This is because we don't want to remove all the spaces between words!

Once again, ther's a bunch of PHP here, but I will go through it carefully with you.

1
2
<?php
3
$fileDirectory = '';
4
$file = $_GET['q'];
5
$nameExplode = explode('.', $file);
6
$ext = $nameExplode[1];
7
$fileName = $fileDirectory . $file;
8
if ($ext != 'css' AND $ext != 'htm' AND $ext != 'html') {
9
	//Check for evil people...
10
	die('Hackers...!');
11
} else {
12
	//Lets get down to business
13
	$handle = fopen($fileName, 'r');
14
	$fileData = fread($handle, filesize($fileName));
15
	//Now for some regex wizzardry!
16
	$newData = preg_replace('/\s+/', ' ', $fileData);
17
	fclose($handle);
18
	//Time to output the data.
19
	if ($ext == 'css') {
20
		header("Content-type: text/css");
21
	}
22
	echo $newData;
23
}
24
?>

Having a Closer Look

This one isn't so tricky, but we will still break it up and make sure we understand what is going on.

We are getting the filename via a parameter passed with the GET request and checking to make sure that it is an allowed filetype. Then we proceed to fetch the data and process it to remove excess whitespace. This method is relatively primitive and won't remove all unnecessary whitespace, but it will deal with most of it in only a few lines of code!

1
2
<?php
3
$fileDirectory = '';
4
$file = $_GET['q'];
5
$nameExplode = explode('.', $file);
6
$ext = $nameExplode[1];
7
$fileName = $fileDirectory . $file;

This snippet just sets some variables. Once again, we are passing our data through 'q' as it is nice and short. This also gives us a place to define our directory for files and extract the file extension. The explode() function rips the filename up whenever it sees a '.' and puts the bits into an array.

1
2
if ($ext != 'css' AND $ext != 'htm' AND $ext != 'html') {
3
	//Check for evil people...
4
	die('Hackers...!');
5
} else {

Here we're checking to make sure that the file is either CSS or HTML. If it was something else we might find ourselves giving hackers a hole into our site like showing them settings.php! So after giving the hackers the flick we can move on to processing our data!

1
2
	//Lets get down to business
3
	$handle = fopen($fileName, 'r');
4
	$fileData = fread($handle, filesize($fileName));
5
	//Now for some regex wizzardry!
6
	$newData = preg_replace('/\s+/', ' ', $fileData);
7
	fclose($handle);
8
	//Time to output the data.
9
	if ($ext == 'css') {
10
		header("Content-type: text/css");
11
	}
12
	echo $newData;
13
}
14
?>

Now for the main attraction; all we are really doing here is opening the file and reading it - like we did in the first script - and then ripping out as much whitespace as possible. This is achieved through a relatively simple regular expression that searches through the file for any spaces, tabs or newlines and then replaces them with a single space.

Lastly we send back the data, setting the required headers if we are dealing with CSS.

But Does it Work?

If you go into your browser and navigate to 'index.php?q=css.css' we should see one line of CSS across the page. This shows that everything is fine! We can also see the same effect on the source code for the html example. In fact in that small example, we reduced a 314 character CSS file down to 277 characters and a 528 character html file down to 448 characters. Not bad for 15 lines of code.

Conclusion

So that's a good example of how we can do quite a lot with very little work. If you have a look at the source of pages like Google you will find that they have almost no whitespace because, when you receive millions of requests, a few extra kilobytes per request really adds up. Unfortunately, most of us aren't that lucky!

3. Caching in your PHP Scripts

In this part, I will show you how to 'retrofit' caching into your scripts using the above script as an example. The aim is to speed things up by not having to regenerate the data every time someone requests a file. Generating the content every request is just a waste, especially on static data such as our CSS.

To add caching we need to add three things to our script. Firstly, we have to collect the data input to the script and generate a filename unique to that set of inputs. Secondly, we have to look for a cache file and see if it is sufficiently recent. Lastly, we have to either use the cached copy or generate new content and cache it for next time.

Breaking the Flow

This part of the process really depends on the individual script, however I will show where I am going to break the flow of this script for the caching.

1
2
<?php
3
$fileDirectory = '';
4
$file = $_GET['q'];
5
$nameExplode = explode('.', $file);
6
$ext = $nameExplode[1];
7
$fileName = $fileDirectory . $file;
8
9
//-- WE HAVE ENOUGH DATA TO GENERATE A CACHE FILE NAME HERE --
10
11
if ($ext != 'css' AND $ext != 'htm' AND $ext != 'html') {
12
	//Check for evil people...
13
	die('Hackers...!');
14
} else {
15
	
16
	//-- WE CAN INTERCEPT AND CHECH FOR THE CACHED VERSION HERE --
17
	
18
	//Lets get down to business
19
	$handle = fopen($fileName, 'r');
20
	$fileData = fread($handle, filesize($fileName));
21
	//Now for some regex wizardry!
22
	$newData = preg_replace('/\s+/', ' ', $fileData);
23
	fclose($handle);
24
	//Time to output the data.
25
	
26
	//-- NOW WE CAN STORE THE NEW DATA IF REQUIRED AND OUTPUT THE DATA --
27
	
28
	if ($ext == 'css') {
29
		header("Content-type: text/css");
30
	}
31
	echo $newData;
32
}
33
?>

Putting it into Action

We will now actually write the code for caching into this script. I will first show the script completed and then go through each piece.

1
2
<?php
3
$fileDirectory = '';
4
$file = $_GET['q'];
5
$nameExplode = explode('.', $file);
6
$ext = $nameExplode[1];
7
$fileName = $fileDirectory . $file;
8
$cacheName = './cache/' . $nameExplode[0] . $nameExplode[1] . '.tmp';
9
if ($ext != 'css' AND $ext != 'htm' AND $ext != 'html') {
10
	//Check for evil people...
11
	print_r($ext);
12
	die('Hackers...!');
13
} else {
14
	if (file_exists($cacheName) AND filemtime($cacheName) > (time() - 86400)) {
15
		$cacheHandle = fopen($cacheName, 'r');
16
		$newData = fread($cacheHandle, filesize($cacheName));
17
		fclose($cacheHandle);
18
		$isCached = TRUE;
19
	} else {
20
		//Lets get down to business
21
		$handle = fopen($fileName, 'r');
22
		$fileData = fread($handle, filesize($fileName));
23
		//Now for some regex wizardry!
24
		$newData = preg_replace('/\s+/', ' ', $fileData);
25
		fclose($handle);
26
		//Lets cache!
27
		$cacheHandle = fopen($cacheName, 'w+');
28
		fwrite($cacheHandle, $newData);
29
		fclose($cacheHandle);
30
		$isCached = FALSE;
31
	}
32
	//Time to output the data.
33
	if ($ext == 'css') {
34
		header("Content-type: text/css");
35
		if ($isCached) {
36
			echo "// Retrieved from cache file. \n";
37
		}
38
	} else {
39
		if ($isCached) {
40
			echo '<!-- Retrieved from cache file. -->';
41
		}
42
	}
43
	echo $newData;
44
	
45
}
46
?>

The Explanation

This one's a bit trickier and a little more likely to leave you scratching you head. But don't worry, not much has changed and we will go through each section. An extra feature we have included is the refreshing of the cache every 24 hours. This is handy so if you change anything, you can either wait 24 hours or simply empty the cache directory. If you want a different refresh interval just calculate it in seconds.

1
2
$cacheName = './cache/' . $nameExplode[0] . $nameExplode[1] . '.tmp';

This bit of code just gets the file's name and extension, glues them together and adds the cache directory and the appropriate '.tmp' extension.

1
2
	if (file_exists($cacheName) AND filemtime($cacheName) > (time() - 86400)) {
3
		$cacheHandle = fopen($cacheName, 'r');
4
		$newData = fread($cacheHandle, filesize($cacheName));
5
		fclose($cacheHandle);
6
		$isCached = TRUE;
7
	} else {

Here we're checking if we have a cache file saved and if the cache file was created within 24 hours. If both these conditions are met then we open the file and extract its contents to substitute for the scripts output. We also set $isCached to true so we can output some messages at the end.

1
2
		//Lets cache!
3
		$cacheHandle = fopen($cacheName, 'w+');
4
		fwrite($cacheHandle, $newData);
5
		fclose($cacheHandle);
6
		$isCache = FALSE;
7
	}

Now we are caching the output of the script for us to use in later requests. We simply open a file in write mode, dump our data into it and then close it. Strictly you don't have to close files in PHP but it's considered a good practise so I have done it here.

1
2
3
	//Time to output the data.
4
	if ($ext == 'css') {
5
		header("Content-type: text/css");
6
		if ($isCached) {
7
			echo "// Retrieved from cache file. \n";
8
		}
9
	} else {
10
		if ($isCached) {
11
			echo '<!-- Retrieved from cache file. -->';
12
		}
13
	}

This is another part of the script that was modified a little so that we can offer some feedback through the browser. If the file was retrieved from the cache we can add a message to the script's output. Notice that the message for CSS scripts has '\n' at the end. This is because the characters '//' comment our entire line and '\n' pushes everything else onto another line. If you want to disable the messages all you have to do is comment out the line '$isCached = TRUE;'.

Giving it a Whirl

If we use our script again, we will notice no change until we refresh a second time when we will see a message saying that the file was retrieved from cache. Sweet success! This caching setup can also be applied to the first script with little modification, however, that is left as an exercise for the reader.

Concluding

Being able to quickly add simple but effective caching to any script that you are working on is an extremely useful skill. It just adds that extra bit to the script, reducing the load on your server and speeding up the site for users. Now that's win-win!

Summing it Up

In this tutorial I have shown you a few handy but simple ways to speed up your site with a dash of PHP. I really hope that you find them useful and that you can apply them to a project in the future. How do you improve your site's performance?


Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.