3 Ways to Speed Up Your Site With PHP

download 3 Ways to Speed Up Your Site With PHP

of 19

Transcript of 3 Ways to Speed Up Your Site With PHP

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    1/19

    3 Ways to Speed up Your Site with PHP

    Thomas Drake-Brockman on Jul 22nd 2009 with127 comments

    These days, with broadband connections the norm, we dont need to worry as much aboutinternet speeds or the filesize of our pages. However, thats not to say that we still shouldnt do so.If you wish to reduce the load times on your server, decrease the number of HTTP requests, and gothat extra bit for your visitors, there are a few techniques that you can use. This tutorial covers anumber 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 logicalseparation and to make modifications easier. However, this increases the number of requests to theserver, 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.

    http://net.tutsplus.com/author/thomasdrake-brockman/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/#commentshttp://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/#commentshttp://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/#commentshttp://net.tutsplus.com/author/thomasdrake-brockman/
  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    2/19

    Preparation

    Before we can optimize CSS files, we will need some CSS to work with! So lets make three filesand put some CSS in them.

    view plain copy to clipboard print ?

    1. // main.css2. // Just some sample CSS3.4. body {5. width: 800px;6. margin: 0 auto;7. color: grey;8. }9.

    10. #wrapper {11. margin-top: 30px;12. background: url(../images/cats.png);13. }

    view plain copy to clipboard print ?

    1. // typography.css2. // Just some sample CSS3.4. body {

    5. font-family: Arial, san-serif;6. font-weight: bold;7. }8.9. strong {10. font-size: 120%;11. }

    view plain copy to clipboard print ?

    1. // forms.css

    2. // Just some sample CSS3.4. form {5. position: relative;6. top: 400px;7. z-index: 99;8. }9.

    http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/
  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    3/19

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    4/19

    Breaking it Down

    It looks quite complicated, but stick with me, its really pretty simple.

    view plain copy to clipboard print ?

    1.

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    5/19

    2. header("Content-type: text/css");3. if (isset($cssData)) {4. echo $cssData;5. echo "\n\n// Generated: " . date("r");6. } else {

    7. echo "// Files not avalable or no files specified.";8. }9. ?>

    The last bit of the script is to send the CSS data to the browser. This means we have to tell PHPthat we are sending CSS data, and that it should inform the browser. We do this with the headerfunction, setting the content type to text/css. Then we send the CSS to the client. We first checkif there is any CSS data to send. If there isnt, then this means that no names of CSS files weresent. If this is the case we simply reply with a CSS comment saying so. If, however, we do havesome data to send, then we send that and add a message detailing when it was generated. If youwanted 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 its time to test the script; we need to first build a directory structure and then place ourscript and CSS files. Have a look at the image below and try to replicate that structure. If you wantsomething different, dont 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 beplaced in the htdocs or www folder of a webserver with PHP (pretty much any webserver thesedays). Navigate to the index.php file. You should be greeted by a single comment: Files notavailable 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 wont cause any problems.

    Lets give something a little trickier a go; type in index.php?q[]=main, you should get the CSSfrom 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 cansend this request: index.php?q[]=main&q[]=forms. As you can see we can repeat q[]= as many

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    6/19

    times as we want because it is adding each value to an array. You could potentially add 50 CSSfiles 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 defaultstyle sheet for every page and and an extra CSS file for pages with forms. Its also easy toimplement if youre already using some sort of CSS processing with PHP. If you want, you caneven rename index.php to index.css as long as you set up .htaccess to treat CSS files as PHP.

    You might notice that Im 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 isnt a problem for you, you may wish to perform a sorting function on the files array beforeprocessing.

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

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    7/19

    2. Stripping Whitespace from your HTML and CSS

    Many of us use large amounts of whitespace when writing code. The good news is that whitespacein PHP doesnt 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. Thismeans that there is some wasted bandwidth. However, with some simple PHP we can remove thisbandwidth leeching whitespace.

    Preparation

    Once again, we will need some raw data to work with; so copy the following example HTML andCSS code. Save the following into a .htm and a .css file in a folder within your servers webrootdirectory.

    view plain copy to clipboard print ?

    1. 3. 4. 5. Hey a Page!6. 7. 8. 9. 10.

    11. Kittens for sale!12. 13. There are lots of spaces here! But we need to get rid of them!14. 15. 16. 17. Lorem Ipsum dol...18. 19. 20. 21.

    view plain copy to clipboard print ?

    1. body {2. min-height: 800px;3. background: black;4. font-size: 18px;5. }

    http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/
  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    8/19

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    9/19

    17. //Time to output the data.18. if ($ext == 'css') {19. header("Content-type: text/css");20. }21. echo $newData;

    22. }23. ?>

    Having a Closer Look

    This one isnt 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 tomake sure that it is an allowed filetype. Then we proceed to fetch the data and process it to removeexcess whitespace. This method is relatively primitive and wont remove all unnecessarywhitespace, but it will deal with most of it in only a few lines of code!

    view plain copy to clipboard print ?

    1.

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    10/19

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

    view plain copy to clipboard print ?

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

    11. echo $newData;12. }13. ?>

    //Lets get down to business$handle = fopen($fileName, 'r');$fileData = fread($handle, filesize($fileName));//Now for some regex wizzardry!$newData = preg_replace('/\s+/', ' ', $fileData);fclose($handle);//Time to output the data.if ($ext == 'css') {

    header("Content-type: text/css");

    }echo $newData;

    }?>

    Now for the main attraction; all we are really doing here is opening the file and reading it like wedid in the first script and then ripping out as much whitespace as possible. This is achievedthrough a relatively simple regular expression that searches through the file for any spaces, tabs ornewlines 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 CSSacross the page. This shows that everything is fine! We can also see the same effect on the sourcecode for the html example. In fact in that small example, we reduced a 314 character CSS filedown to 277 characters and a 528 character html file down to 448 characters. Not bad for 15 linesof code.

    http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/
  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    11/19

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    12/19

    Breaking the Flow

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

    view plain copy to clipboard print ?

    1.

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    13/19

    7.8. //-- WE HAVE ENOUGH DATA TO GENERATE A CACHE FILE NAME HERE --9.10. if ($ext != 'css' AND $ext != 'htm' AND $ext != 'html') {11. //Check for evil people...

    12. die('Hackers...!');13. } else {14.15. //-- WE CAN INTERCEPT AND CHECH FOR THE CACHED VERSION HERE --16.17. //Lets get down to business18. $handle = fopen($fileName, 'r');19. $fileData = fread($handle, filesize($fileName));20. //Now for some regex wizardry!21. $newData = preg_replace('/\s+/', ' ', $fileData);22. fclose($handle);

    23. //Time to output the data.24.25. //-- NOW WE CAN STORE THE NEW DATA IF REQUIRED AND OUTPUT THE D

    ATA --26.27. if ($ext == 'css') {28. header("Content-type: text/css");29. }30. echo $newData;31. }32. ?>

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    14/19

    //-- NOW WE CAN STORE THE NEW DATA IF REQUIRED AND OUTPUT THE DATA --

    if ($ext == 'css') {header("Content-type: text/css");

    }echo $newData;

    }?>

    Putting it into Action

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

    view plain copy to clipboard print ?

    1.

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    15/19

    32. if ($ext == 'css') {33. header("Content-type: text/css");34. if ($isCached) {35. echo "// Retrieved from cache file. \n";36. }

    37. } else {38. if ($isCached) {39. echo '';40. }41. }42. echo $newData;43.44. }45. ?>

  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    16/19

    if ($isCached) {echo '';

    }}echo $newData;

    }?>

    The Explanation

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

    view plain copy to clipboard print ?

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

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

    This bit of code just gets the files name and extension, glues them together and adds the cachedirectory and the appropriate .tmp extension.

    view plain copy to clipboard print ?

    1. if (file_exists($cacheName) AND filemtime($cacheName) > (time() - 86400)) {

    2. $cacheHandle = fopen($cacheName, 'r');3. $newData = fread($cacheHandle, filesize($cacheName));4. fclose($cacheHandle);5. $isCached = TRUE;6. } else {

    if (file_exists($cacheName) AND filemtime($cacheName) > (time() -86400)) {

    $cacheHandle = fopen($cacheName, 'r');$newData = fread($cacheHandle, filesize($cacheName));fclose($cacheHandle);$isCached = TRUE;

    } else {

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

    view plain copy to clipboard print ?

    http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/
  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    17/19

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

    //Lets cache!$cacheHandle = fopen($cacheName, 'w+');fwrite($cacheHandle, $newData);fclose($cacheHandle);$isCache = FALSE;

    }

    Now we are caching the output of the script for us to use in later requests. We simply open a file inwrite mode, dump our data into it and then close it. Strictly you dont have to close files in PHPbut its considered a good practise so I have done it here.

    view plain copy to clipboard print ?

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

    //Time to output the data.if ($ext == 'css') {

    header("Content-type: text/css");if ($isCached) {

    echo "// Retrieved from cache file. \n";}

    } else {if ($isCached) {

    echo '';}

    }

    This is another part of the script that was modified a little so that we can offer some feedbackthrough the browser. If the file was retrieved from the cache we can add a message to the scriptsoutput. 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 todisable the messages all you have to do is comment out the line $isCached = TRUE;.

    http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/http://net.tutsplus.com/tutorials/php/3-ways-to-speed-up-your-site-with-php/
  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    18/19

    Giving it a Whirl

    If we use our script again, we will notice no change until we refresh a second time when we willsee a message saying that the file was retrieved from cache. Sweet success! This caching setup canalso 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 anextremely useful skill. It just adds that extra bit to the script, reducing the load on your server andspeeding up the site for users. Now thats 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 ofPHP. 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 sites performance?

    Follow us on Twitter, or subscribe to the NETTUTS RSS Feed for more daily webdevelopment tuts and articles.

    http://www.twitter.com/nettutshttp://feeds.feedburner.com/nettutshttp://www.twitter.com/nettutshttp://feeds.feedburner.com/nettuts
  • 7/31/2019 3 Ways to Speed Up Your Site With PHP

    19/19

    11diggsdigg