Cache certain areas of your page using PHP

Sometimes it’s necessary to cache only certain elements or areas of your dynamic website to speed up the load times. I recently needed to cache two DIV’s that were being dynamically generated on one of my websites.

Sometimes it’s necessary to cache only certain elements or areas of your dynamic page to speed up the load times. I recently needed to cache two DIV’s that were being dynamically generated on one of my websites. They were each taking about 10 seconds to load which as you know, can be detrimental to your SEO efforts. Here’s the steps I followed in order to reduce my page load times from 20 seconds to under 1.5 seconds.

Step 1: Separate the areas

First of all, you would need to make the areas you would want to cache separate from the page. You can do this by creating new files for these areas and using the “include (‘page_name.php’);” function. This allows us to better control that specific file for caching purposes.

Code:

<div id="pane_popular">
<? 
      // this is one of the divs we want to cache
      include('div_top_articles.php'); 
?>
</div>

Step 2: Create the cache directory
Create a directory called “cache” on your web server. We will reference this in step 3.

Step 3: Insert the PHP cache code

Insert the following script at the top of the included file (in this case it’s the ‘div_top_articles.php’ file).

Code:

<?
    $cachedir = 'cache/'; // Cache directory
    $cachetime = 600; // Seconds to cache files for
    $cacheext = 'cache'; // Extension to give cached files (usually cache, htm, txt)
 
    // Script
    $page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $cachefile = $cachedir.md5($page).'.'.$cacheext; // Cache file to either load or create
 
    $cachefile_created = ((@file_exists($cachefile))) ? @filemtime($cachefile) : 0;
    @clearstatcache();
 
    // Show file from cache if still valid
    if (time() - $cachetime < $cachefile_created) {
 
        //ob_start('ob_gzhandler');
        @readfile($cachefile);
        //ob_end_flush();
 
    }
    else {
    // If we're still here, we need to generate a cache file
 
        ob_start();
 
        // <CONTENT THAT YOU WANT CACHED-->
        // ----------------------------------------------------
        // ----------------------------------------------------
 
        show_latest_articles(10,"latest");
        echo "<small><small>Cached on: ".date("Y-m-d H:i:s")."</small></small>";
 
        // ----------------------------------------------------
        // ----------------------------------------------------
        // 
 
        // Now the script has run, generate a new cache file
        $fp = @fopen($cachefile, 'w'); 
 
        // save the contents of output buffer to the file
        @fwrite($fp, ob_get_contents());
        @fclose($fp); 
 
        ob_end_flush();
    }
 
?>

Code thanks to AddedBytes, modified slightly.

That’s all there is to it.

WordPress 3 error: Warning: Cannot modify header information

This error message has the ability to drive some developers completely insane. However, the solution to this error is A LOT easier than you think.

This error message has the ability to drive some developers completely insane. However, the solution to this error is A LOT easier than you think.

The error:

Wordpress 3 error - Cannot modify header information

What to do

  • Identify the file where the error originates from. This is stated in the actual error. In this case it is “functions.php”, not “theme-editor.php”
  • Remove the white spaces before the “<?php” or “<?” tags as well as after the “?>” tag.

Believe it or not, you are done. Easy as pie.

Extracting a domain name with PHP and Regular Expressions

As most of your know, regular expressions can be a nightmare if you don’t know much about the subject. Here is a quick tutorial on how you can extract the domain name from any URL using regular expressions and PHP. This includes http:// and https:// domain names.

 
<?php 	
$link1 = "http://nickduncan.co.za/";
$link2 = "http://nickduncan.co.za";
$link3 = "http://www.nickduncan.co.za/";
$link4 = "http://www.nickduncan.co.za";
 
$link5 = "https://nickduncan.co.za/";
$link6 = "https://nickduncan.co.za";
$link7 = "https://www.nickduncan.co.za/";
$link8 = "https://www.nickduncan.co.za";
 
$link9 = "http://www.nickduncan.co.za/index.php";
$link10 = "http://www.nickduncan.co.za/index.php?id=34&that=this";
$link11 = "http://nickduncan.co.za/php-header-include-%E2%80%93-saving-development-time/";
 
echo return_domain($link1)." - ".$link1;
echo "<br />".return_domain($link2)." - ".$link2;
echo "<br />".return_domain($link3)." - ".$link3;
echo "<br />".return_domain($link4)." - ".$link4;
echo "<br />".return_domain($link5)." - ".$link5;
echo "<br />".return_domain($link6)." - ".$link6;
echo "<br />".return_domain($link7)." - ".$link7;
echo "<br />".return_domain($link8)." - ".$link8;
echo "<br />".return_domain($link9)." - ".$link9;
echo "<br />".return_domain($link10)." - ".$link10;
echo "<br />".return_domain($link11)." - ".$link11;
 
 
function return_domain($link) {
    $domain = preg_match('@^(?:https?://)?([^/]+)@i', $link, $matches);
    return $matches[1];
}
?>

Another easy method is to use the PHP function called parse_url which returns certain elements of a URI that you choose. For examples on this function, consult the PHP manual which has more than enough examples.

Stopping SQL Injections

SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed.

SQL Injections can leave your website crippled and useless and most developers haven’t even thought about this. Do you know what a SQL injection is? Here is the official definition:

SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another. SQL injection attacks are also known as SQL insertion attacks.

How they do it
SQL injections can be inserted through the use of your website’s forms as well as your global variables. An attacker would analyse your forms and attempt to manipulate the way you insert data into your database.

Example:
Lets say one of your pages is as follows:
http://examples.co.za/product.php?product=salt
And the attacker adds ‘ or ‘a’=’a to the end of the URI like such: http://examples.co.za/product.php?product=salt’ or ‘a’=’a
What this is essentially doing is changing your unprotected SQL query to something like
SELECT * FROM product WHERE product=’salt’ or ‘a’=’a’
Instead of the query now looking for products that equal ‘salt’, it now selects everything regardless! By using this in a log in form the attacker may be able to gain access to the site without actually logging in. This is an extremely easy method of manipulating your query. There are a lot more malicious techniques out there.

What to do
If you are using a solid framework you are relatively safe but in actual fact, SQL injections are hard to stop as there are many ways to pull this off. Here are some steps you can take to ensure some heartless moron doesn’t come along and wipe your database off the face of the earth or worse, gain access to passwords you don’t want them to know about and wreak more havoc.

Sanitizing Function
This simple yet effective sanitizing function escapes special characters in a string for use in a SQL statement.

<?php
  function sanitize_slash($string) {
    // make sure you are connected to your DB before attempting to return this function
    return mysql_real_escape_string($string);
  }
?>

The above method will add a ‘\’ to single and double quotes to ensure your query cannot be manipulated. The next method eliminates ALL special characters except for a-z, A-Z and 0-9. Your choice is dependent on your websites functionality.

<?php
  function sanitize_all($string) {
    return preg_replace( "/[^a-zA-Z0-9 ]/i", "", $string );
  }
?>

For example, if you would like to sanitize the input of a text field, use the first function. If you would like to sanitize the input of a users username, use the second function.

Example:

<?php
  $aboutme = sanitize_slash($_POST['website']);
  $firstname = sanitize_all($_POST['firstname']);
  $surname = sanitize_all($_POST['surname']);
  $email = sanitize_slash($_POST['email']);
  // you should get the picture now...
?>

Another good method to use in conjunction with these functions is to check if the given input is the expected data type. IE: If you are expecting a number format, double check it with the is_numeric() function.

One last thing to remember, make sure you turn off error_reporting(); The last thing you need is to show the attacker the database error details!

<?php error_reporting(1); //add this right at the beginning of your file ?>

So in closing, make sure you follow these steps to try and eliminate any potential attacks that may occur:

  • Never trust user input.
  • Sanitize your variables before attempting to insert them in a SQL query.
  • Make sure your form < input > names are not the same as your table’s field names.
  • Make sure you double check expected data types.
  • Turn off error_reporting()

Good luck and as always, if you have anything to add to this, please feel free to insert your suggestions or examples below.

PHP Header Include – Saving development time

I have had the opportunity to go through a lot of other developers coding skills and practices in the past few months and I must admit there is a lot of time wasting going on. Are you the type of developer that has a <title>, <meta>, <link> and <body> tag on every page without a global include? If so, let me show you how to simplify your life.

I have had the opportunity to go through a lot of other developers coding skills and practices in the past few months and I must admit there is a lot of time wasting going on. Are you the type of developer that has a <title>, <meta>, <link> and <body> tag on every page without a global include? If so, let me show you how to simplify your life.

By having a global header include you can set all your title tags in one central location as well as control which page gets what header information all in one file.

Firstly, create a file called header.php and use the below template:

header.php

<?php
	// Get the filename of the current page;
	$cpage = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1);
 
	// set this to a "default" title as a backup incase you forget to mention a page. This stops it from returning nothing.
	$wtitle = "My Default Website Title";
 
	// Control page titles
	switch ($cpage) {
		case "index.php": $wtitle = "Home page title"; break;
		case "contact_us.php": $wtitle = "Contact us"; break;
		case "products.php": $wtitle = "Products Page"; break;
		case "about_us.php": $wtitle = "About us"; break;
	}
 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head>
  	<title><?php echo $wtitle; ?></title>
  	<meta name="robots" content="index,follow,all" />
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 
	<link rel="stylesheet" href="css/style.css" type="text/css" />
	<?php
		// if you're on the products page, load the products.css file.
		if ($cpage == "products.php") { echo '<link rel="stylesheet" href="css/products.css" type="text/css" />'; }
	?>
</head>
 
 
<body>
 
 
<div id="wrapper">

Now you can start creating all your other pages and simply include the header.php file right at the top as follows:

index.php / contact_us.php / products.php / about_us.php

<?php include "header.php"; ?>
 
<div id="content">
<p>Content goes here</p>
</div>
 
<?php include "footer.php"; ?>

As you can see we have taken this one step further and also created a footer.php file. This comes in very handy when you need to put tracking code at the bottom of ever page. Instead of pasting it on every single file, simply paste it into the footer.php.

footer.php

</div>
 
</body>
</html>

I hope you find this as valuable as I do. If you do it differently please give us the details. After all, we all learn from each other.