Articles

Planet PHP

Planet PHP is a feed aggregator blog specifically for PHP related blogs. There are a good number of blogs that the site uses to update with so there is always plenty of stuff going up on the site. The site is not run by PHP, and is an independent project run by Christian Stocker and Tobias Schlitt.

Manage MySQL Databases With phpMyAdmin

The good thing about this site is that it saves having to go through all of the blogs in turn to see what is interesting in the world of PHP. If you run a PHP blog you can submit your site to the list and get your articles included in the updates.

Writing Function Code To Be More Readable

Last month I started writing functions in a particular way, which has made my life as a programmer much easier on more than one occasion. No matter how many comments or verbose parameter names you put in you can end up writing code that you will get lost in. The reason is simple. Lets say you had a function that took in a couple of parameters.

function myFunction($intNum1, $intNum2){
 // function does something
}

Normal practice is to check the parameters to make sure that they are what you expected them to be before continuing on with the rest of the function. Let's say that we only want the numbers to be in a range. If they are not in the range the function should return false. Many programmers might start of writing something like this.

Simple Swear Filter In PHP

Use the following function to filter out words from user input. It works by having a pre-set array of words that are to be excluded, this array is then looped through and each item is used to replace any instances of that word within the text. The regular expression uses the \b character class, which stands for any word boundary. This way you don't get the middle of words being filtered out when they are not meant to be.

By using the e of the preg_replace function it is possible to run PHP functions within the output. In this case we count the number of characters found in the replace and use this to create a string of stars (*) of equal length.

Search Engine Spider Detection With PHP

Part of any search engine optimisation strategy should always be that the user and the search engine see the same thing. If you start delivering different content you will either end up not performing or just getting outright banned. However, there are certain circumstances where you will want to detect the presence of a search engine spider. For example, let's say that you had a link to a section of your site, and you wanted to add a counter to it that registered an action every time a user clicked on the link. One way of doing this would be to add a parameter to the URL of the link, if the parameter is present then it is a user going through the site and so the action will be registered. You don't want to register every time a search engine bot spiders the site so using the following function will allow you to turn off this parameter for these spiders.

Directory Iteration With DirectoryIterator() In PHP 5

The normal way of looping through a directory is to get a handle on the directory, then go through each item, making sure that the file is readable and is not "." or ".." before doing something with the file. Because this is done a lot the DirectoryIterator() object was created in PHP5 to simplify this process.

The constructor of the DirectoryIterator() object takes a single parameter, this is the path of the directory that is to be iterated over.

$dir = new DirectoryIterator('/');

To get the current working directory you can use the PHP function getcwd(). This will return the directory that the PHP script is being run from.

$dir = new DirectoryIterator(getcwd());

The previous bit of code will open up the root directory of your server. If you are on a Linux server you will see directories like dev, var, srv, etc, lib, home, root, sbin and usr.

Pad A String In JavaScript

Use the following function to pad a string with to a set length with a given string. The function takes three parameters. The string to be padded, the total number of characters that the string must be, and the string to be added. If the third parameter is not given then 0 is used as a default.

function pad(padMe, totalChars, padWith) {
  padMe = padMe + ""; // force num to be string
 padWith = (padWith) ? padWith :"0"; // set default pad
 if ( padMe.length < totalChars ) {
  while ( padMe.length < totalChars ) {
    padMe = padWith + padMe;
  }
 }
 return padMe;
}

Here are some examples of the function in action. If the string given is longer than the required pad length then the string is returned unchanged.

JavaScript Word Counter

Counting the number of words in a block of text can be tricky. Users tend to create sections of white space that can throw out most scripts that don't take this into consideration.

I have created a tool for #! code that looks at a textarea of a form, and prints the number of words into an input box in the same form. The textarea calls a function called textCounter() every time a key is pressed. Here is the HTML of the form.

<form onsubmit="return false;" action="" id="wordCountCalc">
<textarea name="message1" rows="10" cols="68" onkeydown="textCounter()" onkeyup="textCounter()"></textarea>
<input readonly="readonly" size="15" type="text" name="len" maxlength="10" value="0" />
</form>

The function works by removing any white space from the start of the text. It then removes any tab characters from the text before splitting the text by one or more white space characters.

Limit Number Of Rows Returned In MS SQL

To limit the number of rows returned in a MS SQL query you need to use the TOP command. This goes before you name the columns that are to be returned by the SELECT statement.

The following query returns the first 35 rows from a table.

Regular Expression To Find Single Apersands In Text

Encoding special characters in a block of HTML or other code can be a pain because there might already be ampersands there that impart encoding. This might be an ampersand that has already been encoded with a &amp;, or it might be an ampersand in the code as an if statement or similar.

Use the following regular expression to find any ampersand that hasn't already been encoded.

([^&])&(?!#?[a-zA-Z0-9]{2,6};|\$|&)

When using replace, you can turn any ampersand into &amp; by using the following replace.

$1&amp;

The only problem with this statement is when the code uses a & operator as part of a statement to do bitwise operations.

Finding Missing Values In A MySQL Table

If you have a table of incremental values it can be hard to find out which ones are missing. The only solution might be to write a script to get all the data from the database and see which ones are missing. However, there is a way of doing this without using a script.

Using a standard select query like this:

SELECT * FROM table;

Gets the following data:

1
3
10
23

We can see that values are missing, but which ones? The following query will show us where the gaps are in the data of the table.

SELECT t1.id+1 as Missing
FROM table as t1
LEFT JOIN table  as t2 ON t1.id+1 = t2.id
WHERE t2.id IS NULL
ORDER BY t1.id;

Produces the following result.