PHP

Getting An Excerpt Of Text With PHP

I have talked before about truncating strings to include whole words, but what if you want to have complete sentences? The following function will truncate a string the number of words specified and until the sentence ends.

function excerpt($paragraph, $limit)
{
 $tok = strtok($paragraph, " ");
 while ($tok !== false) {
  $text .= " ".$tok;
  $words++;
  if (($words >= $limit) && ((substr($tok, -1) == "!") || (substr($tok, -1) == ".") || (substr($tok, -1) == "?"))) {
   break;
  }
  $tok = strtok(" ");
 }
 return ltrim($text);
}

Using this function you can create an excerpt of any text you want, as long as it has a sentence in it. Take the following section of text.

Work Out The Number Of Days Before A Date

Use the following function to work out the number of days between today and a date in the future. The function takes three parameters of the day, month and year of the date in question.

<?php
function dateDifference($day, $month, $year)
{
 return (int)((mktime (0, 0, 0, $month, $day, $year) - time(void))/86400);
}
?>

To use this function just give it a date, here are some examples.

echo dateDifference(13,07,2008); // 42
echo dateDifference(01,01,2010); // the next "binary date" = 579
echo dateDifference(25,12,2010); // 937

 

Controlling Error Reporting On Different Servers With PHP

Having a testing server is quite a common practice, but what happens when you want to go live and you don't want all of your error messages displayed?

A good way of doing this is to create a variable that you can then use to detect what server your code is running on and set your error displaying accordingly. The following section of code will set a variable to true if the code is not running on the server name www.hashbangcode.com. This variable is then used to set the error reporting level.

<?php
 $turnOnErrors = $_SERVER['SERVER_NAME'] != 'www.hashbangcode.com';
 
 if ( $turnOnErrors ) {
  error_reporting(E_ALL);
  ini_set('display_errors', 1);
 } else {
  error_reporting(0);
  ini_set('display_errors', 0);
 }
?>

 

Transform Text Links Into Anchors

Using the strip_tags() function on any user generated input should be common practice in order to stop users putting in odd bits of HTML and messing up your nicely coded HTML. You might want to allow anchor tags to be used, which is fine, but some users might use this to include onmouseover and other events in order to run JavaScript annoyances on the page.

So after stripping all tags from your text you can then run the following function to turn any links into anchor elements. This will work with any plain text that you want to use it on.

Very Simple PHP Visit Counter

To create a simple PHP visit counter you will need to create a plain blank text file called counter.txt.

Put the following two functions into a file and include it at the top of any page that you want to have counted.

The loadCounter() function.
function loadCounter()
{
 if ( file_exists('counter.txt') ) {
  $n = file_get_contents('counter.txt');
  return intval($n);
 }
 return 0;
}

The updateCounter() function.

function updateCounter($i=1)
{
 
 $n = loadCounter();
 $n += $i;
 
 $fp = fopen('counter.txt',"w+");
 fwrite($fp, $n);
 fclose($fp);
 
 return $n;
}

The two functions work together to create the counter. If you only want to display the number of times that a page has been visited then just call the loadCounter() function.

List All Files In A Directory By Creation Date

The following function takes a path as an argument and produces an array of files ordered by their timestamp. The array values are the filename and the array keys are the timestamps. In order to prevent two files that have the same timestamp overwriting each other when the array keys are created with a random number. If two files where created at the same time the least that will happen is that they will swap places every time the array is created as the random number will be different.

function listDirectoryByDate($path) {
 $dir = opendir($path);
 $list = array();
 while ($file = readdir($dir)) {
  if ($file != '.' && $file != '..' && !is_dir($file)) {
   $ctime = filectime($path.$file) . rand(1000,9999);
   $list[$ctime] = $file;
  }
 }
 closedir($dir);
 krsort($list);
 return $list;
}

To use the function to print out all of the files in the current directory use the following code.

Display A String By A Date Value With PHP

Printing off a random quote on a page is useful (or at least interesting), but it is nice to rotate them slower than every page view.

A better solution is to use a time based value to work out which quote to display. In this way the quote is changed every hour/day/week or whatever time period you have selected.

Create a file called quote.txt in the same directory as the script and put a single quote on each line.

quote 1
quote 2
quote 3

The following function will take a time part as a single parameter and return a quote.

Generate A Random Colour With PHP

Here is a short bit of code to generate a random hexadecimal colour using PHP. Essentially you just create a random number between 0 (000000) and 10,000,000 (ffffff) and turn this into a hexadecimal number using the PHP function dechex.

$colour = rand(0, 10000000);
$colour = dechex($colour);

This can also be accomplished on a single line.

$colour = dechex(rand(0, 10000000));

Blocking Multiple IP Addresses With PHP

It is sometimes necessary to block people from using your site, dependent on their IP address. A users IP address can be detected by PHP using the $_SERVER superglobal and the parameter REMOTE_ADDR.

The code includes two ways to load the list of IP addresses. The first is by hard coding it into an array, and the second is by the use of a plain text file called "blocked_ips.txt". The format of this file is simply a list of IP addresses, with one address on each line. Through the use of the file() function this file is loaded as an array into of addresses.

Function To Darken A Colour With PHP

The following function will reduce a hexadecimal colour string by a set value. It can take three and six digit colour values.

function ColourDarken($colour, $dif=20)
{
 $colour = str_replace('#','', $colour);
 $rgb = '';
 if (strlen($colour) != 6) {
  // reduce the default amount a little
  $dif = ($dif==20)?$dif/10:$dif;
  for ($x = 0; $x < 3; $x++) {
   $c = hexdec(substr($colour,(1*$x),1)) - $dif;
   $c = ($c < 0) ? 0 : dechex($c);
   $rgb .= $c;
  }
 } else {
  for ($x = 0; $x < 3; $x++) {
   $c = hexdec(substr($colour, (2*$x),2)) - $dif;
   $c = ($c < 0) ? 0 : dechex($c);
   $rgb .= (strlen($c) < 2) ? '0'.$c : $c;
  }
 }
 return '#'.$rgb;
}

Here are some examples of use.

echo ColourDarken('#123456'); // #002042
echo ColourDarken('#666'); // #444
echo ColourDarken('#ffffff'); // #ebebeb
echo ColourDarken('#ffffff',1); // #eeeeee