PHP

Posts about the server side scripting language PHP

Alternate If Statements In PHP

If you have programmed in PHP for any amount of time then you will be farmiliar with the if statement. The syntax is as follows:

if($something == $somethingelse){
  //do something
}elseif($something == $anotherthing){
  //do another thing
}else{
  // default action
}

The PHP engine also allows you to do what I call "lazy programming" where you don't need the curly braces. Only the line underneath the if statement is run if the if clause if met.

if($something == $somethingelse)
  // do something

The issue here is that when this is put into the rest of the program the code becomes almost unreadable and therefore unmaintainable. The curly brases make it much easier to see what a program is doing. For readability and maintenance, many developers consider it bad style not to include them.

Aborting Connections In PHP

Sometimes in PHP you will have to do some things that might take a little time. You will therefore have a little trouble with users closing the browser or moving to another page before the script has finished. In this case you will want to either continue to execute the script just shut it down depending on what the user has done.

PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent. Use the flush() function after the echo call to force PHP to sent output information to the browser.

To run the script to the end no matter what the user has done use the ignore_user_abort() function with the parameter of true.

ignore_user_abort(true);

This might be useful if you are recording things to a database so that data integrity is still maintained.

How To Read A Remote IP Address In PHP

PHP keeps certain variables to do with server and networking in an associative array called SERVER. To find out the remote address of a user you can use the array identifier REMOTE_ADDR. This is used in the following manner.

$ipaddress = $_SERVER['REMOTE_ADDR'];

This IP address can be passed into the gethostbyaddr() function to find out host name associated with the specified IP address.

Redirecting The Page In PHP

To redirect the current page to a different location you use the header() function in the following way:

header("http://www.hashbangcode.com");

You can use this function when you want to point the user to a different page. If you are writing a login script then this function would be useful to show the user a certain page depending on them entering the correct user information.

Highlight Code In PHP

When printing off source code there is a handy function that will parse the code and produce nice looking syntax highlighted code. There are actually two functions you can use. The highlight_string() function takes a string as a parameter and will print the highlighted code. The highlight_file() function takes a file name as a parameter, the contents of which are printed off with highlighted syntax. For now I will concentrate on the highlight_string() function, but the output of these two functions is the same.

To use the highlight_string() function just pass it a string. The following code:

highlight_string('<?php 
function checkslash($slashes_string){
  if (get_magic_quotes_gpc()==1) {
    return $slashes_string;
  }else{
    return addslashes($slashes_string);
  };
};
?>');

Will produce the following output:

Check Slash on Database Input

If you are querying a database you should get into the habit of sanitising your input, even if it's not coming from users at the moment it might do in the future. SQL injection attacks are all too common and they can be easily prevented.

The addslashes() function takes a string as the input and returns a string with backslashes before all characters that required quoting in database queries. The characters it acts on are quote, double quote, backslash and NUL (or a NULL byte). Magic quotes runs addslashes() on all COOKIE, GET and POST data. The important thing is not to use addslashes() and magic quotes on the same string as everything will be double escaped.

Use the get_magic_quotes_gpc() function to see if magic quotes is enabled. If it isn't then use the PHP function addslashes() to do the same thing. Use this function if you have any user input in order to sanitise anything that you are about to send to a database.

PHP Website Function Lookup

Those of you who have coded in PHP must have looked at the PHP website at some point, even if it was just to down load the latest version, or to look up a function reference.

What most people don't realise is that there is a really easy way to go straight to the page that you want without having to mess around with the tetchy search engine on the PHP site.

Lets say you wanted to know about the function phpinfo(). This is a debugging function that displays everything you could possible imagine about the PHP environment and is usually used by people who are just starting out with the language as it prints a lot of stuff to the screen.

To look at the reference for the phpinfo() function you could go to the following URL.

PHP Array Mode Function

The following mode function will return the most commonly occurring value from an array of values, also called the mode. If just the array is used then only the most commonly occurring value will be returned. The second parameter can be used to return an array containing the mode and the number of times that this value occurs in the array.

Rounding A Number To Nearest The Thousand In PHP

I have previously talked about rounding numbers in PHP, but what if you wanted to round the number to the nearest thousand?

It is possible to do this with the native round() function in PHP by using a negative number as the second parameter. The round() function has two parameters, the first is the number to be rounded and the second is the number of places to round the number to, also known as the precision. The default for round() is to round the number to the nearest whole number, by using positive numbers as the second parameter you can set the number of decimal places to round the number to. Giving a negative number as the second parameter will allow you to round the number to the nearest full number. For example, to round a number to the nearest thousand you can put -3 as the precision, this will change the number 12,345 into 12000.

Generate A Radio Button Group With PHP

Here is a function to create a group of radio buttons in a HTML form. The three parameters are:

  1. $name : The name of the radio group.
  2. $options : An associative array of items to be included in the group of radio buttons.
  3. $default : The default value of the radio buttons.
function createRadio($name,$options,$default=''){
  $name = htmlentities($name);
  $html = '';
  foreach($options as $value=>$label){
    $value = htmlentities($value);
    $html .= '<input type="radio" ';
    if($value == $default){
      $html .= ' checked="checked" ';
    };
    $html .= ' name="'.$name.'" value="'.$value.'" />'.$label.'<br />'."\n";
  };
  return $html;
}

You can call the function in the following way: