Thursday 12 April 2012

How to implement CAPTCHA in PHP?

CAPTCHA is used to prevent spam abuse on the websites.

If we have a public submission form on our website (contact Us page), we can use CAPTCHA.
We can discuss how we can implement CAPTCHA in PHP

1. Create a php file that generates image.(say CaptchaImages.php)

<?php
session_start();
class CaptchaSecurityImages {
    var $font = 'Teen Bold.ttf';
    function generateCode($characters) {
        /* list all possible characters, similar looking characters and vowels have been removed */
        $possible = '23456789bcdfghjkmnpqrstvwxyz';
        $code = '';
        $i = 0;
        while ($i < $characters) {
            $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
            $i++;
        }
        return $code;
    }

    function CaptchaSecurityImages($width='120',$height='40',$characters='6') {
        $code = $this->generateCode($characters);
        /* font size will be 75% of the image height */
        $font_size = $height * 0.75;
        $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
        /* set the colours */
        $background_color = imagecolorallocate($image, 255, 255, 255);
        $text_color = imagecolorallocate($image, 20, 40, 100);
        $noise_color = imagecolorallocate($image, 100, 120, 180);
        /* generate random dots in background */
        for( $i=0; $i<($width*$height)/3; $i++ ) {
            imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
        }
        /* generate random lines in background */
        for( $i=0; $i<($width*$height)/150; $i++ ) {
            imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height),

$noise_color);
        }
        /* create textbox and add text */
        $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
        $x = ($width - $textbox[4])/2;
        $y = ($height - $textbox[5])/2;
        imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext

function');
        /* output captcha image to browser */
        header('Content-Type: image/jpeg');
        imagejpeg($image);
        imagedestroy($image);
        $_SESSION['security_code'] = $code;
    }
}
$width = isset($_GET['width']) ? $_GET['width'] : '120';
$height = isset($_GET['height']) ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) && $_GET['characters'] > 1 ? $_GET['characters'] : '6';
$captcha = new CaptchaSecurityImages($width,$height,$characters);
?>



2. Copy paste “Teen Bold.ttf” font in the same directory as the CaptchaImages.php file. (Alternatively you can replace the line var $font = ‘Teen Bold.ttf’; with the name of whatever font you want to use)
You can download the font from http://www.webpagepublicity.com/free-fonts-t.html#Free%20Fonts


3. Put the below code in the form.
    <input id="security_code" name="security_code" type="text" />
    <img src="CaptchaImages.php?width=100&height=40&characters=5" />
    (you can specify the width and height of the image)

4. Put the below code in the form . It check the generated captcha image with the image you have submitted in the text box.

   <?php
      session_start();
   if( isset($_POST['submit'])) {
   if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {      
        unset($_SESSION['security_code']);
           if($_SERVER["REQUEST_METHOD"] == "POST"){
             // process email
        }
     } else {
            // validation message
               unset($_SESSION['security_code']);
   }
  }
?>

************************************************************************************
Php example which contains the contact form:


 <?php
 error_reporting(0);
 session_start();
if( isset($_POST['submit'])) {
   if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
       
        unset($_SESSION['security_code']);
           if($_SERVER["REQUEST_METHOD"] == "POST"){
               $to = "someone@example.com";
            $subject = $_POST['subject'];
            $message = $_POST["textarea"];
            $from = $_POST["email"];
            $headers = "From:" . $from;
            mail($to,$subject,$message,$headers);
        }
     } else {
        echo "<br/>";
        echo "<b>";
        echo "<div align='left'>";
        echo "<font color='red'>". 'Sorry, you have provided an invalid security code'."</font>";
        echo "</div>";
        echo "</b>";
        unset($_SESSION['security_code']);
   }
 
}
?>
 <form name="form1" id="form1" method="post" action="">
                                  <table border="0" width="350" style="font-size:12px;">
                                    <tbody>
                                    <tr>
                                      <td>
                                        <label for="label"> <strong>Email</strong></label>
                                        <label for="label">:</label>
                                       *</td>
                                       <td >
                                          <input type="text" id="email" name="email">
                                       </td>
                                    </tr>
                                    <tr>
                                      <td height="28"><label for="txtemail"> <strong>Subject:</strong>
                                      </label>
                                       *</td>
                                       <td height="28">
                                          <input type="text" id="subject" name="subject">
                                      </td>
                                    </tr>
                                                                       <tr>
                                      <td height="30">
                                      <label for="label2"> <strong>Message:</strong></label>
                                       *</td>
                                       <td>
                                          <textarea id="textarea" name="textarea" rows="5" cols="17"></textarea>
                                     </td>
                                    </tr>
                                         <tr> </tr>
                                    <tr>
                                      <td>
                                      <label for="security_code"><Strong>Security Code:</Strong> </label>
                                      *
                                    <br/></td>
                                    <td>
                                            <input id="security_code"

name="security_code" type="text" /><br />
                                        </td>
                                       
                                    </tr>
                                    <tr>
                                      <td><div align="left">
                                          <img src="CaptchaImages.php?width=140&height=40&characters=5" />
                                           
                                        </div></td>
                                    </tr>
                                  
                                  
                                   
                                    <tr>
                                      <td height="32"><div align="center"><strong></strong></div></td>
                                    </tr>
                                    <tr>
                                      <td><div align="center">
                                          <input type="submit"   value="Send Message" name="submit">
                                      </div></td>
                                    </tr>
                                  </tbody></table>
                                </form>

Wednesday 11 April 2012

Table sorting in php using javascript?

The below example sort the table using java script. you can populate the table data from database using php.
You need to create 2 folders css and js. put the table.css in css folder and table.js in js folder.
copy paste the below code and save it as sort.php and put it in pages folder.

Download table.js and table.css

<html>
<head>
    <meta charset="UTF-8" />
    <title>Php table sort</title>
    <link rel="stylesheet" type="text/css" href="../css/table.css" />
    <script src="../js/table.js" type="text/javascript"></script>
</head>
<?php
error_reporting(0);
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("genedb", $con);
$sql="SELECT * FROM gene";

$result = mysql_query($sql);
       ?>
       <div id="content">
        <div id="blog">
        <div id="articles" style="width:692px;padding:0;">
<table width="250" border="1" class="example table-autosort table-autofilter table-autopage:10 table-stripeclass:alternate table-page-number:t1page table-page-count:t1pages table-filtered-rowcount:t1filtercount table-rowcount:t1allcount" id="t1">
<thead>
    <tr style="height:35px">
        <th class="table-sortable:default table-sortable table-sorted-desc">Symbol</th>
        <th class="table-sortable:numeric table-sortable  " title="Click to sort">Id</th>
        <th class="table-filterable table-sortable:default table-sortable" title="Click to sort">Location</th>
        </tr>
</thead>
<tbody>
    <?php
    while($row = mysql_fetch_array($result))
  {     
       ?>
 <tr>
 <td><?php echo $row['symbol']?></td>
 <td><?php echo $row['id']?></td>
 <td><?php echo $row['location']?></td>
  <?php
  }
  mysql_close($con);
?>
 </tbody>
 <tfoot>
   
    <tr>
        <td style="cursor:pointer;" class="table-page:previous">&lt; &lt; Previous</td>
        <td style="text-align:center;" colspan="1">Page <span id="t1page">1</span>&nbsp;of <span id="t1pages">11</span></td>
        <td style="cursor:pointer;" class="table-page:next">Next &gt; &gt;</td>
    </tr>
    <tr>
        <td colspan="3"><span id="t1filtercount">105</span>&nbsp;of <span id="t1allcount">105</span>&nbsp;rows match filter(s)</td>
</tr></tfoot>
</table>

Output :




                                                                                technorati claim code :A8CRZ8P6MW44 

Thursday 5 April 2012

Get the value of t:inputCalendar if readonly is true


<t:inputCalendar id="cal" value="#{backingBean.date1}"
        renderAsPopup="true"
        popupDateFormat="MM/dd/yyyy"
        popupTodayDateFormat="dd-MMM-yyyy"
        popupWeekString="Week"
        popupTodayString="The date today is :"
        renderPopupButtonAsImage="true"
        helpText="MM/DD/YYYY"
        readonly="true"/>

To get the value in the backing bean just add the below code.
When readonly attribute is true, the component cannot be edited by the user.(ie the text box in the calendar cannot be edited.)

bodyId:id of body tag
formId:id of form tag
String dateString = (String) getExternalContext().getRequestParameterMap().get("bodyId:formId:date1");

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy",
                 getCurrentLocale());


                                                                                        



Wednesday 4 April 2012

How to Wrap text in a cell of a html table?

Normally wrapping of text happens automatically in HTML tables.But if the text contains no delimiters(like "Thisisatext" instead of  "This is a Text"), word wrapping does not happens.

Below code works even if there is no delimiters in the text.

<table width="700" style="table-layout:fixed" align="left">
<tr>
<td style="word-wrap: break-word;">
</td>
</tr>
</table>