Simple Pagination in PHP tutorial

Pagination is a frequent requirement in web development projects. Most PHP developers must have already implementated paging in one form or other in their projects. In this post we will see how to add pagination the easy way using PEAR’s Pager class. Note that in all the posts I use PHP 5.x.x, so if you are still stuck at version 4.x.x, its already time to upgrade.
Read More

Ping a server using PHP

PEAR’s Net_Ping is a niffty wrapper class for executing ping calls from PHP. You can use it to check if a remote server is responding correctly. The library can be download from¬† here.

Installation

Net_Ping being a Pear package we will use the Pear installer to download and install it. I recommend to always use the Pear installer to download packages rather than downloading it manually as the Pear installer automatically downloads any dependent packages.

pear install Net_Ping-2.4.4

Usage

A example of using Net_Ping is given below.
Read More

Reading raw POST data in PHP

A quick tip for reading raw http POST data in PHP. For example if we have a xml posted to a page, we can read the raw data with the following code.

$xml = file_get_contents('php://input');

We could use $HTTP_RAW_POST_DATA instead, but many times it does not work due to some php.ini settings. Note that ‘php://input’ does not work with enctype=”multipart/form-data”.

converting MySQL queries to xml

There frequently arises a need to return mySQL query results in xml. Maybe you need to send the xml data to the browser or you want to use it as a xml request to a web service; whatever the application, the following function will return the result of a sql query in xml format.

The function accepts 3 parameters. The first is the mysql query result resource, the second is the name of the root element and the third the name of the first child of the root. All the fields from the mySQL table will be sub elements of this child.

The function is shown below:
Read More

Luhn algorithm for validating credit cards

The Luhn algorithm also known as the “modulus 10” or “mod 10” algorithm, is a checksum formula which can be used to validate credit card numbers. Developed in the 1950’s by IBM scientist Hans Peter Luhn and described in U.S. Patent 2,950,048. A PHP implementation is shown below.


function LuhnCheck($strDigits)
{
    $sum = 0;
    $alt = false;
    for($i = strlen($strDigits) - 1; $i >= 0; $i--) 
    {
        if($alt)
        {
           $temp = $strDigits[$i];
           $temp *= 2;
           $strDigits[$i] = ($temp > 9) ? $temp = $temp - 9 : $temp;
        }
        $sum += $strDigits[$i];
        $alt = !$alt;
    }
    return $sum % 10 == 0;
}