Quick Contact

    Implementing CAPTCHA

    A CAPTCHA , an acronym for Completely Automated Public Turing test to tell Computers and Humans Apart is a type of challenge–response test used in computing to determine whether the user is human or not.

    Captcha is basically a random generate captcha string and which can be stored in session variable for further use. We can use PHP to construct a CAPTCHA.

    This user identification procedure has received many criticisms, especially from disabled people, but also from other people who feel that their everyday work is slowed down by distorted words that are difficult to read. It takes the average person approximately 10 seconds to solve a typical CAPTCHA.

    Consider an example:

    We us easiest CAPTCHA scripts. While it doesn’t obscure the text, it will serve its purpose well for many people who need a low-level CAPTCHA solution. This script requires little-to-no setup. The only dependency is the PHP GD library.

    Example CAPTCHA image:

    CAPTCHASample image

    It can be as simple as this to use, but it is also configurable:

    phpTextCaptcha

    phpTextCaptcha is open-source free PHP CAPTCHA script to create complex images and protect forms from spam and abuse.

    The features of phpTextCaptcha are given below:

    • Small code structure.
    • It’s using phptextClass to create captcha image.
    • Customizable code.
    • Security features such as random lines and noise.

    Consider a program for CAPTCHA where we need three different files:

    phpTextClass.php

    This file is Main class file with phpcaptcha, hexToRGB and ImageTTFCenter function.

    <?php
    {
    public function phpcaptcha($textColor,$backgroundColor,$imgWidth,$imgHeight,$noiceLines=0,$noiceDots=0,$noiceColor='#162453')
    {
    /* Settings */$text=$this->random();
    $font = './font/monofont.ttf';/* font */$textColor=$this->hexToRGB($textColor);
    $fontSize = $imgHeight * 0.75;
    
    $im = imagecreatetruecolor($imgWidth, $imgHeight);
    $textColor = imagecolorallocate($im, $textColor['r'],$textColor['g'],$textColor['b']);
    
    $backgroundColor = $this->hexToRGB($backgroundColor);
    $backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']);
    
    /* generating lines randomly in background of image */if($noiceLines>0){
    $noiceColor=$this->hexToRGB($noiceColor);
    $noiceColor = imagecolorallocate($im, $noiceColor['r'],$noiceColor['g'],$noiceColor['b']);
    for( $i=0; $i<$noiceLines; $i++ ) {
    imageline($im, mt_rand(0,$imgWidth), mt_rand(0,$imgHeight),
    mt_rand(0,$imgWidth), mt_rand(0,$imgHeight), $noiceColor);
    }}
    
    if($noiceDots>0){/* generating the dots randomly in background */for( $i=0; $i<$noiceDots; $i++ ) {
    imagefilledellipse($im, mt_rand(0,$imgWidth),
    mt_rand(0,$imgHeight), 3, 3, $textColor);
    }}
    
    imagefill($im,0,0,$backgroundColor);
    list($x, $y) = $this->ImageTTFCenter($im, $text, $font, $fontSize);
    imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text);
    
    imagejpeg($im,NULL,90);/* Showing image */header('Content-Type: image/jpeg');/* defining the image type to be shown in browser widow */imagedestroy($im);/* Destroying image instance */if(isset($_SESSION)){
    $_SESSION['captcha_code'] = $text;/* set random text in session for captcha validation*/}
    }
    
    /*function to convert hex value to rgb array*/protected function hexToRGB($colour)
    {
            if ( $colour[0] == '#' ) {
    $colour = substr( $colour, 1 );
            }
            if ( strlen( $colour ) == 6 ) {
    list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
            } elseif ( strlen( $colour ) == 3 ) {
    list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
            } else {
    return false;
            }
            $r = hexdec( $r );
            $g = hexdec( $g );
            $b = hexdec( $b );
            return array( 'r' => $r, 'g' => $g, 'b' => $b );
    }
    
    
    /*function to get center position on image*/protected function ImageTTFCenter($image, $text, $font, $size, $angle = 8) 
    {
    $xi = imagesx($image);
    $yi = imagesy($image);
    $box = imagettfbbox($size, $angle, $font, $text);
    $xr = abs(max($box[2], $box[4]))+5;
    $yr = abs(max($box[5], $box[7]));
    $x = intval(($xi - $xr) / 2);
    $y = intval(($yi + $yr) / 2);
    return array($x, $y);
    }
    
    Demo.php

    This file is used to obtain submitted form data and used to validate captcha image.

    <?php session_start();
    
    if(isset($_POST['Submit'])){
    // code for check server side validation
    if(empty($_SESSION['captcha_code'] ) || strcasecmp($_SESSION['captcha_code'], $_POST['captcha_code']) != 0){  
    $msg="<span style='color:red'>The Validation code does not match!</span>";// Captcha verification is incorrect.
    }else{// Captcha verification is Correct. Final Code Execute here!
    $msg="<span style='color:green'>The Validation code has been matched.</span>";
    }
    }
    ?>
    
    <form action="" method="post" name="form1" id="form1" >
    <table width="400" border="0" align="center" cellpadding="5" cellspacing="1" class="table">
    <?php if(isset($msg)){?>
    <tr>
    <td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
    </tr>
    <?php } ?>
    <tr>
    <td align="right" valign="top"> Validation code:</td>
    <td><img src="captcha.php?rand=<?php echo rand();?>" id='captchaimg'><br>
    <label for='message'>Enter the code above here :</label>
    <br>
    <input id="captcha_code" name="captcha_code" type="text">
    <br>
            Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh.</td>
    </tr>
    <tr>
    <td></td>
    <td><input name="Submit" type="submit" onclick="return validate();" value="Submit" class="button1"></td>
    </tr>
    </table>
    </form>
    
    Captcha.php

    This file is used to generate captcha image.

    <?php
    session_start();
    include("./phptextClass.php");
    
    /*create class object*/$phptextObj = new phptextClass();
    /*phptext function to genrate image with text*/$phptextObj->phpcaptcha('#162453','#fff',120,40,10,25);
     ?>
    
    PDF Generation

    The PDF functions in PHP can create PDF files using the PDFlib library from PDFlib GmbH. A restricted version called PDFlib Lite 7 is available for free, but it is no longer maintained since 2010. PDFlib integration for PHP is still actively maintained by PDFlib GmbH. It is mainly targeted at the commercial PDFlib versions but can also be used for the old PDFlib Lite.

    If you want to use PDFlib we urge you start with the examples which are included in all PDFlib packages and refer to the extensive manuals in PDF format which are also included. At a minimum you should take a look at the hello.php sample to learn basic setup for PDFlib usage.

    Most of the functions are fairly easy to use. The most difficult part is probably creating your first PDF document. The following example should help to get you started. It is developed for PHP 4 and creates the file hello.pdfwith one page. It defines some document info field contents, loads the Helvetica-Bold font and outputs the text Hello world! (says PHP).

    Consider an example of PDF creation

    <?php
    $p = PDF_new();
    /*  open new PDF file; insert a file name to create the PDF on disk */
    if (PDF_begin_document($p, "", "") == 0) {
        die("Error: " . PDF_get_errmsg($p));
    }
    PDF_set_info($p, "Creator", "hello.php");
    PDF_set_info($p, "Author", "Rainer Schaaf");
    PDF_set_info($p, "Title", "Hello world (PHP)!");
    PDF_begin_page_ext($p, 595, 842, "");
    $font = PDF_load_font($p, "Helvetica-Bold", "winansi", "");
    PDF_setfont($p, $font, 24.0);
    PDF_set_text_pos($p, 50, 700);
    PDF_show($p, "Hello world!");
    PDF_continue_text($p, "(says PHP)");
    PDF_end_page_ext($p, "");
    PDF_end_document($p, "");
    $buf = PDF_get_buffer($p);
    $len = strlen($buf);
    header("Content-type: application/pdf");
    header("Content-Length: $len");
    header("Content-Disposition: inline; filename=hello.pdf");
    print $buf;
    
    PDF_delete($p);
    ?>
    

    The following example comes with the PDFlib distribution for PHP 5. It uses the new exception handling and object encapsulation features available in PHP 5. It creates the file hello.pdf with one page. It defines some document info field contents, loads the Helvetica-Bold font and outputs the text “Hello world! (says PHP).

    <?php
    
    try {
        $p = new PDFlib();
    
        /*  open new PDF file; insert a file name to create the PDF on disk */
        if ($p->begin_document("", "") == 0) {
            die("Error: " . $p->get_errmsg());
        }
    
        $p->set_info("Creator", "hello.php");
        $p->set_info("Author", "Rainer Schaaf");
        $p->set_info("Title", "Hello world (PHP)!");
    
        $p->begin_page_ext(595, 842, "");
    
        $font = $p->load_font("Helvetica-Bold", "winansi", "");
    
        $p->setfont($font, 24.0);
        $p->set_text_pos(50, 700);
        $p->show("Hello world!");
        $p->continue_text("(says PHP)");
        $p->end_page_ext("");
        $p->end_document("");
    
        $buf = $p->get_buffer();
        $len = strlen($buf);
    
        header("Content-type: application/pdf");
        header("Content-Length: $len");
        header("Content-Disposition: inline; filename=hello.pdf");
        print $buf;
    }
    catch (PDFlibException $e) {
        die("PDFlib exception occurred in hello sample:\n" .
        "[" . $e->get_errnum() . "] " . $e->get_apiname() . ": " .
        $e->get_errmsg() . "\n");
    }
    catch (Exception $e) {
        die($e);
    }
    $p = 0;
    ?>
    

    We can also use FPDF for PDF generation. FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs.

    FPDF has other advantages: high level functions. Here is a list of its main features:

    • Choice of measure unit, page format and margins
    • Page header and footer management
    • Automatic page break
    • Automatic line break and text justification
    • Image support (JPEG, PNG and GIF)
    • Colors
    • Links
    • TrueType, Type1 and encoding support
    • Page compression

    FPDF requires no extension (except Zlib to enable compression and GD for GIF support). The latest version requires at least PHP 5.1.

    Excel or CSV Generation

    We can find out various methods of creating different format files with PHP.

    Create MS Excel document

    Method 1 – Using HTTP headers

    As described for the MS Word, you need to format the HTML/PHP page using Excel-friendly CSS and add header information to your PHP script.

    <?php
    header("Content-type: application/vnd.ms-excel");
    header("Content-Disposition: attachment;Filename=document_name.xls");
    echo "<html>";
    echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
    echo "<body>";
    echo "<b>testdata1</b> \t <u>testdata2</u> \t \n ";
    echo "</body>";
    echo "</html>";
    ?>
    
    Method 2 – Using COM objects

    Note that the server running the code stated below must have MS Excel installed. We use the same approach as for MS Word with saving a file to the temporary directory first.

    ...
    //Create new COM object – excel.application
    $xl = new COM("excel.application");
    //Hide MS Excel application window
    $xl->Visible = 0;
    //Create new document
    $xlBook = $xl->Workbooks->Add();
    //Create Sheet 1
    $xlBook->Worksheets(1)->Name = "Worksheet 1";
    $xlBook->Worksheets(1)->Select;
    //Set Width & Height
    $xl->ActiveSheet->Range("A1:A1")->ColumnWidth = 10.0;
    $xl->ActiveSheet->Range("B1:B1")->ColumnWidth = 13.0;
    //Add text
    $xl->ActiveSheet->Cells(1,1)->Value = "TEXT";
    $xl->ActiveSheet->Cells(1,1)->Font->Bold = True;
    //Save document
    $filename = tempnam(sys_get_temp_dir(), "excel");
    $xlBook->SaveAs($filename);
    //Close and quit
    unset( $xlBook);
    $xl->ActiveWorkBook->Close();
    $xl->Quit();
    unset( $xl );
    header("Content-type: application/vnd.ms-excel");
    header("Content-Disposition: attachment;Filename=document_name.xls");
    // Send file to browser
    readfile($filename);
    unlink($filename);
    ...
    
    Create a CSV file

    We can use below two methods to create a CSV file using PHP.

    Method 1 – Using HTTP headers

    As in the examples for the Word and Excel, you need to add header information to your PHP script.

    The code snippet below creates a CSV file of the specified table including its column names. Then user will be prompted to download this file.

    <?php
    $table = 'table_name';
    $outstr = NULL;
    header("Content-Type: application/csv");
    header("Content-Disposition: attachment;Filename=cars-models.csv");
    $conn = mysql_connect("localhost", "mysql_user", "mysql_password");
    mysql_select_db("db",$conn);
    // Query database to get column names  
    $result = mysql_query("show columns from $table",$conn);
    // Write column names
    while($row = mysql_fetch_array($result)){
        $outstr.= $row['Field'].',';
    }  
    $outstr = substr($outstr, 0, -1)."\n";
    // Query database to get data
    $result = mysql_query("select * from $table",$conn);
    // Write data rows
    while ($row = mysql_fetch_assoc($result)) {
        $outstr.= join(',', $row)."\n";
    }
    
    echo $outstr;
    mysql_close($conn);
    ?>
    
    Method 2 – Using fputcsv()

    The fputcsv() function formats a line as CSV and writes it to an open file.

    The code snippet below creates a CSV file of the specified table including its column names and sends it to the browser.

    <?php 
    $table = 'table_name';
    $filename = tempnam(sys_get_temp_dir(), "csv");
    
    $conn = mysql_connect("localhost", "mysql_user", "mysql_password");
    mysql_select_db("db",$conn);
    
    $file = fopen($filename,"w");
    
    // Write column names
    $result = mysql_query("show columns from $table",$conn);
    for ($i = 0; $i < mysql_num_rows($result); $i++) {
        $colArray[$i] = mysql_fetch_assoc($result);
        $fieldArray[$i] = $colArray[$i]['Field'];
    }
    fputcsv($file,$fieldArray);
    
    // Write data rows
    $result = mysql_query("select * from $table",$conn);
    for ($i = 0; $i < mysql_num_rows($result); $i++) {
        $dataArray[$i] = mysql_fetch_assoc($result);
    }
    foreach ($dataArray as $line) {
        fputcsv($file,$line);
    }
    
    fclose($file);
    
    header("Content-Type: application/csv");
    header("Content-Disposition: attachment;Filename=cars-models.csv");
    
    // send file to browser
    readfile($filename);
    unlink($filename);
    ?>
    
    Email with PHP

    PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].

    Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.

    The configuration for Windows should look something like this:

    [mail function]
    ; For Win32 only.
    SMTP = smtp.secureserver.net
    
    ; For win32 only
    sendmail_from = webmaster@ducat.com
    

    Linux users simply need to let PHP know the location of their sendmailapplication. The path and any desired switches should be specified to the sendmail_path directive.

    The configuration for Linux should look something like this:

    [mail function]
    ; For Win32 only.
    SMTP = 
    
    ; For win32 only
    sendmail_from = 
    
    ; For Unix only
    sendmail_path = /usr/sbin/sendmail -t -i
    

    PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient’s email address, the subject of the the message and the actual message additionally there are other two optional parameters.

    mail( to, subject, message, headers, parameters );

    Here is the description for each parameter.

    • to: It specifies the receiver / receivers of the email.
    • subject: Subject specifies the subject of the email. This parameter cannot contain any newline characters.
    • message: It defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters.
    • headers: This field specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n).
    • parameters: It specifies an additional parameter to the send mail program.

    As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.

    Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.

    Sending HTML email

    When you send a textmessage using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.

    While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

    Following example will send an HTML email message to xyz@somedomain.com copying it to afgh@somedomain.com. You can code this program in such a way that it should receive all content from the user and then it should send an email.

    <html>
    <head>
    <title>Sending HTML email using PHP</title>
    </head>
    <body>
    <?php
             $to = "xyz@somedomain.com";
             $subject = "This is subject";
    
             $message = "<b>This is HTML message.</b>";
             $message .= "<h1>This is headline.</h1>";
    
             $header = "From:abc@somedomain.com \r\n";
             $header .= "Cc:afgh@somedomain.com \r\n";
             $header .= "MIME-Version: 1.0\r\n";
             $header .= "Content-type: text/html\r\n";
    
             $retval = mail ($to,$subject,$message,$header);       
             if( $retval == true ) {
                echo "Message sent successfully...";
             }else {
                echo "Message could not be sent...";
             }
          ?>
    </body>
    </html>
    
    Sending attachments with email

    To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.

    A boundary is started with two hyphens followed by a unique number which cannot appear in the message part of the email. A PHP function md5() is used to create a 32-digit hexadecimal number to create unique number. A final boundary denoting the email’s final section must also end with two hyphens.

    <?php
       // request variables // important
       $from = $_REQUEST["from"];
       $emaila = $_REQUEST["emaila"];
       $filea = $_REQUEST["filea"];
    
       if ($filea) {
          function mail_attachment ($from , $to, $subject, $message, $attachment){
             $fileatt = $attachment; // Path to the file
             $fileatt_type = "application/octet-stream"; // File Type 
    
             $start = strrpos($attachment, '/') == -1 ? 
                strrpos($attachment, '//') : strrpos($attachment, '/')+1;
    				
             $fileatt_name = substr($attachment, $start, 
                strlen($attachment)); // Filename that will be used for the 
                file as the attachment 
    
             $email_from = $from; // Who the email is from
             $subject = "New Attachment Message";
    
             $email_subject =  $subject; // The Subject of the email 
             $email_txt = $message; // Message that the email has in it 
             $email_to = $to; // Who the email is to
    
             $headers = "From: ".$email_from;
             $file = fopen($fileatt,'rb'); 
             $data = fread($file,filesize($fileatt)); 
             fclose($file); 
    
             $msg_txt="\n\n You have recieved a new attachment message from $from";
             $semi_rand = md5(time()); 
             $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
             $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . "
                boundary=\"{$mime_boundary}\"";
    
             $email_txt .= $msg_txt;
    			
             $email_message .= "This is a multi-part message in MIME format.\n\n" . 
                "--{$mime_boundary}\n" . "Content-Type:text/html; 
                charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . 
                $email_txt . "\n\n";
    				
             $data = chunk_split(base64_encode($data));
    
             $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" .
                " name = \"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" . 
                //" filename = \"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: 
                base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";
    				
             $ok = mail($email_to, $email_subject, $email_message, $headers);
    
             if($ok) {
                echo "File Sent Successfully.";
                unlink($attachment); // delete a file after attachment sent.
             }else {
                die("Sorry but the email could not be sent. Please go back and try again!");
             }
          }
          move_uploaded_file($_FILES["filea"]["tmp_name"],
             'temp/'.basename($_FILES['filea']['name']));
    			
          mail_attachment("$from", "youremailaddress@gmail.com", 
             "subject", "message", ("temp/".$_FILES["filea"]["name"]));
       }
    ?>
    
    <html>
    <head>
    
    <script language = "javascript" type = "text/javascript">
             function CheckData45() {
                with(document.filepost) {
                   if(filea.value ! = "") {
                      document.getElementById('one').innerText = 
                         "Attaching File ... Please Wait";
                   }
                }
             }
    </script>
    
    </head>
    <body>
    
    <table width = "100%" height = "100%" border = "0" 
             cellpadding = "0" cellspacing = "0">
    <tr>
    <td align = "center">
    <form name = "filepost" method = "post" 
                      action = "file.php" enctype = "multipart/form-data" id = "file">
    
    <table width = "300" border = "0" cellspacing = "0" 
                         cellpadding = "0">
    							
    <tr valign = "bottom">
    <td height = "20">Your Name:</td>
    </tr>
    
    <tr>
    <td><input name = "from" type = "text" 
                               id = "from" size = "30"></td>
    </tr>
    
    <tr valign = "bottom">
    <td height = "20">Your Email Address:</td>
    </tr>
    
    <tr>
    <td class = "frmtxt2"><input name = "emaila"
                               type = "text" id = "emaila" size = "30"></td>
    </tr>
    
    <tr>
    <td height = "20" valign = "bottom">Attach File:</td>
    </tr>
    
    <tr valign = "bottom">
    <td valign = "bottom"><input name = "filea" 
                               type = "file" id = "filea" size = "16"></td>
    </tr>
    
    <tr>
    <td height = "40" valign = "middle"><input 
                               name = "Reset2" type = "reset" id = "Reset2" value = "Reset">
    <input name = "Submit2" type = "submit" 
                               value = "Submit" onClick = "return CheckData45()"></td>
    </tr>
    </table>
    
    </form>
    
    <center>
    <table width = "400">
    
    <tr>
    <td id = "one">
    </td>
    </tr>
    
    </table>
    </center>
    
    </td>
    </tr>
    </table>
    
    </body>
    </html>
    
    Implementing Pagination

    Pagination is essentially the process of taking a set of results and spreadingthem out over pages to make them easier to view.

    Paginator

    This example will be composing of two scripts, the reusable paginator class and the index file that will display the table items and controls.

    Paginator.class.php

    The paginator class will have only two methods and the constructor, we will build it gradually explaining each step as we move forward.

    <?php
    class Paginator {
    
         private $_conn;
            private $_limit;
            private $_page;
            private $_query;
            private $_total;
    }
    

    This definition only set’s the paginator required member variables, since this is a helper class and it’s destined for pagination only it will rely on a valid connection to the MySQL server and an already defined query that we will append the parameters necessary to paginate the results. We’ll start with the constructor method.

    <?php
    public function __construct( $conn, $query ) {     
        $this->_conn = $conn;
        $this->_query = $query;
    
        $rs= $this->_conn->query( $this->_query );
        $this->_total = $rs->num_rows;
    
    }
    

    Quite simple right? This method only set’s the object’s database connection and the necessary query, after that it calculates the total number of rows retrieved by that query without any limit nor skip parameters, this total is necessary to create the links for the paginator.

    Note that for simplicity we are not doing error checking or any other validation of the given parameters, but in a real world application this checks will be necessary.

    Retrieving Results

    Now let’s create the method that will actually paginate the data and return the results.

    <?php
    public function getData( $limit = 10, $page = 1 ) {
    
        $this->_limit   = $limit;
        $this->_page    = $page;
    
        if ( $this->_limit == 'all' ) {
            $query      = $this->_query;
        } else {
            $query      = $this->_query . " LIMIT " . ( ( $this->_page - 1 ) * $this->_limit ) . ", $this->_limit";
        }
        $rs             = $this->_conn->query( $query );
    
        while ( $row = $rs->fetch_assoc() ) {
            $results[]  = $row;
        }
    
        $result         = new stdClass();
        $result->page   = $this->_page;
        $result->limit  = $this->_limit;
        $result->total  = $this->_total;
        $result->data   = $results;
    
        return $result;
    }
    

    Let’s analyze this one step at a time, first we set the limit and page parameters, which by default are set the 10 and 1 respectively. Then we check if the user is requiring a given number of rows or all of them, base on this and the page parameter we set the LIMIT parameter of the query, the “- 1” of the page is taking into account the fact that we are starting the pages in 1 instead of 0.

    After this we simply evaluate the query and get the results, finally we create a new results object which contain the limit, page and total parameters of the executed query as well as the data for each of the retrieved rows.

    Displaying Pagination Links

    Now let’s write the method used to get the pagination links.

    <?php
    public function createLinks( $links, $list_class ) {
        if ( $this->_limit == 'all' ) {
            return '';
        }
    
        $last       = ceil( $this->_total / $this->_limit );
    
        $start      = ( ( $this->_page - $links ) > 0 ) ? $this->_page - $links : 1;
        $end        = ( ( $this->_page + $links ) < $last ) ? $this->_page + $links : $last;
    
        $html       = '<ul class="' . $list_class . '">';
    
        $class      = ( $this->_page == 1 ) ? "disabled" : "";
        $html       .= '<li class="' . $class . '"><a href="?limit=' . $this->_limit . '&page=' . ( $this->_page - 1 ) . '">«</a></li>';
    
        if ( $start > 1 ) {
            $html   .= '<li><a href="?limit=' . $this->_limit . '&page=1">1</a></li>';
            $html   .= '<li class="disabled"><span>...</span></li>';
        }
    
        for ( $i = $start ; $i <= $end; $i++ ) {
            $class  = ( $this->_page == $i ) ? "active" : "";
            $html   .= '<li class="' . $class . '"><a href="?limit=' . $this->_limit . '&page=' . $i . '">' . $i . '</a></li>';
        }
    
        if ( $end < $last ) {
            $html   .= '<li class="disabled"><span>...</span></li>';
            $html   .= '<li><a href="?limit=' . $this->_limit . '&page=' . $last . '">' . $last . '</a></li>';
        }
    
        $class      = ( $this->_page == $last ) ? "disabled" : "";
        $html       .= '<li class="' . $class . '"><a href="?limit=' . $this->_limit . '&page=' . ( $this->_page + 1 ) . '">»</a></li>';
    
        $html       .= '</ul>';
    
        return $html;
    }
    

    This is a rather long method, something like 34 lines of code, so now let’s explain what is going on in this method.

    1. First we evaluate if the user is requiring a given number of links or all of them, in the second case we simply return an empty string since no pagination is required.
    2. After this we calculate the last page based on the total number of rows available and the items required per page.
    3. Then we take the links parameter which represents the number of links to display below and above the current page, and calculate the start and end link to create.
    4. Now we create the opening tag for the list and set the class of it with the list class parameter and add the “previous page” link, note that for this link we check if the current page is the first, and if so, we set the disabled property of the link.
    5. At this point we display a link to the first page and an ellipsis symbol in case that the start link is not the first one.
    6. Next we add the links below and above the current page based on the previously calculated start and end parameters, in each step we evaluate the current page again the link page displayed and set the active class accordingly.
    7. After this we display another ellipsis symbol and the link to the last page in case that the end link is not the last one.
    8. Finally we display the “next page” link and set the disabled state when the user is viewing the last page, close the list and return the generated HTML string.

    That’s all there is to the Paginator.class, of course we could add setters and getters for the database connection, limit, page, query and total parameters but for simplicity we’ll keep it this way.

    Index.php

    Now we’ll create the file in charge of using the Paginator class and displaying the data, so first let me show you the base HTML.

    <!DOCTYPE html>
    <head>
    <title>PHP Pagination</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    </head>
    <body>
    <div class="container">
    <div class="col-md-10 col-md-offset-1">
    <h1>PHP Pagination</h1>
    <table class="table table-striped table-condensed table-bordered table-rounded">
    <thead>
    <tr>
    <th>City</th>
    <th width="20%">Country</th>
    <th width="20%">Continent</th>
    <th width="25%">Region</th>
    </tr>
    </thead>
    <tbody></tbody>
    </table>
    </div>
    </div>
    </body>
    </html>
    

    Quite simple, this file only displays a table that we will populate with the information retrieved from the database, note that for this example I’m using bootstrap for basic page styling.

    Using the Paginator
    <?php for( $i = 0; $i < count( $results->data ); $i++ ) : ?>
    <tr>
    <td><?php echo $results->data[$i]['Name']; ?></td>
    <td><?php echo $results->data[$i]['Country']; ?></td>
    <td><?php echo $results->data[$i]['Continent']; ?></td>
    <td><?php echo $results->data[$i]['Region']; ?></td>
    </tr>
    <?php endfor; ?>
    

    Now for make use of our Paginator class add the following php code at the top of the document.

    <?php
        require_once 'Paginator.class.php';
    
        $conn       = new mysqli( '127.0.0.1', 'root', 'root', 'world' );
    
        $limit      = ( isset( $_GET['limit'] ) ) ? $_GET['limit'] : 25;
        $page       = ( isset( $_GET['page'] ) ) ? $_GET['page'] : 1;
        $links      = ( isset( $_GET['links'] ) ) ? $_GET['links'] : 7;
        $query      = "SELECT City.Name, City.CountryCode, Country.Code, Country.Name AS Country, Country.Continent, Country.Region FROM City, Country WHERE City.CountryCode = Country.Code";
    
        $Paginator  = new Paginator( $conn, $query );
    
        $results    = $Paginator->getData( $page, $limit );
    ?>
    

    This script is quite simple, we just required our Paginator class, note that this code assumes that this file is in the same directory as the index.php file, if this is not the case you should update the path accordingly.

    Then we create the connection to our database using the MySQLi library, retrieve the paginator parameters from the GET request and set the query, since this is not an article on MySQL or any of that I will not get into details about the connection or the query used here.

    Lastly, we create the Paginator object and retrieve the results for the current page.

    Displaying the Results

    Now to display the obtained results add the following code to the table body.

    <?php for( $i = 0; $i < count( $results->data ); $i++ ) : ?>
    <tr>
    <td><?php echo $results->data[$i]['Name']; ?></td>
    <td><?php echo $results->data[$i]['Country']; ?></td>
    <td><?php echo $results->data[$i]['Continent']; ?></td>
    <td><?php echo $results->data[$i]['Region']; ?></td>
    </tr>
    <?php endfor; ?>
    
    Web Services with JSON

    JSON is acronym for JavaScript Object Notation. JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation.

    PHP has some built-in functions to handle JSON.Objects in PHP can be converted into JSON by using the PHP function json_encode();

    An example is given below:

    <?php
    $myObj->name = "John";
    $myObj->age = 30;
    $myObj->city = "New York";
    
    $myJSON = json_encode($myObj);
    
    echo $myJSON;
    ?>
    
    The Client JavaScript

    Here is a JavaScript on the client, using an AJAX call to request the PHP file from the example above:

    An example is shown below:

    Use JSON.parse() to convert the result into a JavaScript object:

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            document.getElementById("demo").innerHTML = myObj.name;
        }
    };
    xmlhttp.open("GET", "demo_file.php", true);
    xmlhttp.send();
    
    Exception Handling

    Exceptions are used to change the normal flow of a script if a specified error occurs.With PHP 5 came a new object-oriented way of dealing with errors.

    Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

    This is what normally happens when an exception is triggered:

    • The current code state is saved
    • The code execution will switch to a predefined (custom) exception handler function
    • Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code

    The following are the error handling methods:

    • Basic use of Exceptions
    • Creating a custom exception handler
    • Multiple exceptions
    • Re-throwing an exception
    • Setting a top-level exception handler
    Basic Use of Exceptions

    When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching “catch” block.

    If an exception is not caught, a fatal error will be issued with an “Uncaught Exception” message.

    Let’s try to throw an exception without catching it:

    <?php
    //create function with an exception
    function checkNum($number) {
      if($number>1) {
        throw new Exception("Value must be 1 or below");
      }
      return true;
    }
    
    //trigger exception
    checkNum(2);
    ?>
    

    The code above will get an error like this:

    Fatal error: Uncaught exception ‘Exception’ with message ‘Value must be 1 or below’ in C:\webfolder\test.php:6 Stack trace: #0 C:\webfolder\test.php(12): checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

    Try, throw and catch

    To avoid the error from the example above, we need to create the proper code to handle an exception.

    Proper exception code should include:

    1. Try: A function using an exception should be in a tryblock. If the exception does not trigger, the code will continue as normal. However, if the exception triggers, an exception is thrown
    2. Throw: This is how you trigger an exception. Each throw must have at least one catch
    3. Catch: A catch block retrieves an exception and creates an object containing the exception information

    Let’s try to trigger an exception with valid code:

    <?php
    //create function with an exception
    function checkNum($number) {
      if($number>1) {
        throw new Exception("Value must be 1 or below");
      }
      return true;
    }
    
    //trigger exception in a "try" block
    try {
      checkNum(2);
      //If the exception is thrown, this text will not be shown
      echo 'If you see this, the number is 1 or below';
    }
    
    //catch exception
    catch(Exception $e) {
      echo 'Message: ' .$e->getMessage();
    }
    ?>
    

    The code above will get an error like this:

    Message: Value must be 1 or below

    The code above throws an exception and catches it:

    1. The checkNum() function is created. It checks if a number is greater than 1. If it is, an exception is thrown
    2. The checkNum() function is called in a “try” block
    3. The exception within the checkNum() function is thrown
    4. The “catch” block retrieves the exception and creates an object ($e) containing the exception information
    5. The error message from the exception is echoed by calling $e->getMessage() from the exception object

    However, one way to get around every throw must have a catch rule is to set a top-level exception handler to handle errors that slip through.

    Creating a Custom Exception Class

    To create a custom exception handler, you must create a special class with functions that can be called when an exception occurs in PHP. The class must be an extension of the exception class.

    The custom exception class inherits the properties from PHP’s exception class and you can add custom functions to it.

    Let’s create an exception class:

    <?php
    class customException extends Exception {
      public function errorMessage() {
        //error message
        $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
        .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
        return $errorMsg;
      }
    }
    
    $email = "someone@example...com";
    
    try {
      //check if
      if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
        //throw exception if email is not valid
        throw new customException($email);
      }
    }
    
    catch (customException $e) {
      //display custom message
      echo $e->errorMessage();
    }
    ?>
    

    The new class is a copy of the old exception class with an addition of the errorMessage() function. Since it is a copy of the old class, and it inherits the properties and methods from the old class, we can use the exception class methods like getLine() and getFile() and getMessage().

    Example explained:

    The code above throws an exception and catches it with a custom exception class:

    1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
    2. The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
    3. The $email variable is set to a string that is not a valid e-mail address
    4. The “try” block is executed and an exception is thrown since the e-mail address is invalid
    5. The “catch” block catches the exception and displays the error message
    Multiple Exceptions

    It is possible for a script to use multiple exceptions to check for multiple conditions.

    It is possible to use several if..else blocks, a switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:

    <?php
    class customException extends Exception {
      public function errorMessage() {
        //error message
        $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
        .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
        return $errorMsg;
      }
    }
    
    $email = "someone@example.com";
    
    try {
      //check if
      if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
        //throw exception if email is not valid
        throw new customException($email);
      }
      //check for "example" in mail address
      if(strpos($email, "example") !== FALSE) {
        throw new Exception("$email is an example e-mail");
      }
    }
    
    catch (customException $e) {
      echo $e->errorMessage();
    }
    
    catch(Exception $e) {
      echo $e->getMessage();
    }
    ?>
    

    Example explained:

    The code above tests two conditions and throws an exception if any of the conditions are not met:

    1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
    2. The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
    3. The $email variable is set to a string that is a valid e-mail address, but contains the string “example”
    4. The “try” block is executed and an exception is not thrown on the first condition
    5. The second condition triggers an exception since the e-mail contains the string “example”
    6. The “catch” block catches the exception and displays the correct error message

    If the exception thrown were of the class customException and there were no customException catch, only the base exception catch, the exception would be handled there.

    Re-throwing Exceptions

    Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way. It is possible to throw an exception a second time within a “catch” block.

    A script should hide system errors from users. System errors may be important for the coder but are of no interest to the user. To make things easier for the user you can re-throw the exception with a user-friendly message:

    <?php
    class customException extends Exception {
      public function errorMessage() {
        //error message
        $errorMsg = $this->getMessage().' is not a valid E-Mail address.';
        return $errorMsg;
      }
    }
    
    $email = "someone@example.com";
    
    try {
      try {
        //check for "example" in mail address
        if(strpos($email, "example") !== FALSE) {
          //throw exception if email is not valid
          throw new Exception($email);
        }
      }
      catch(Exception $e) {
        //re-throw exception
        throw new customException($email);
      }
    }
    
    catch (customException $e) {
      //display custom message
      echo $e->errorMessage();
    }
    ?>
    

    The example is explained as:

    The code above tests if the email-address contains the string example in it, if it does, the exception is re-thrown:

    1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
    2. The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
    3. The $email variable is set to a string that is a valid e-mail address, but contains the string example
    4. The try block contains another try block to make it possible to re-throw the exception
    5. The exception is triggered since the e-mail contains the string example
    6. The catch block catches the exception and re-throws a customException
    7. The customException is caught and displays an error message

    If the exception is not caught in its current “try” block, it will search for a catch block on higher levels.

    Set a Top-Level Exception Handler

    The set_exception_handler() function sets a user-defined function to handle all uncaught exceptions:

    <?php
    function myException($exception) {
      echo "<b>Exception:</b> " . $exception->getMessage();
    }
    
    set_exception_handler('myException');
    
    throw new Exception('Uncaught Exception occurred');
    ?>
    

    The output of the code above should be something like this:

    Exception: Uncaught Exception occurred

    In the code above there was no catch block. Instead, the top-level exception handler triggered. This function should be used to catch uncaught exceptions.

    Rules for exceptions
    • Code may be surrounded in a try block, to help catch potential exceptions
    • Each try block or “throw” must have at least one corresponding catch block
    • Multiple catch blocks can be used to catch different classes of exceptions
    • Exceptions can be thrown (or re-thrown) in a catch block within a try block

    A simple rule: If you throw something, you must catch it.

    Summary

    The points below summarize the topics discussed:

    • A CAPTCHA, an acronym for Completely Automated Public Turing test to tell Computers and Humans Apart is a type of challenge–response test used in computing to determine whether the user is human or not.
    • We can use PHP to construct CAPTCHA for web applications.
    • PHP can be used to generate Excel and CSV (Comma Separated Values).
    • To send email through PHP, one must configure php.ini file.
    • Pagination is essentially the process of taking a set of results and spreading them out over pages to make them easier to view.
    • JSON (JavaScript Object Notation) can be used with PHP to generate web services.
    • Exception handling is used to change the normal flow of the code execution if a specified error condition occurs. There is numerous way in PHP to handle exceptions.

    Copyright 1999- Ducat Creative, All rights reserved.