Showing posts with label Php. Show all posts
Showing posts with label Php. Show all posts

Wednesday 15 May 2013

Php mail tagged as Spam in Gmail Issue fixed

Issue

When I send mail using PHP mail() function,the mail is sent to the Spam folder in GMail.

Solution

You can fix this issue by using the fifth parameter in the mail function to build the header with a valid From address.

PHP Code

<?php 
 
$to 
'you@gmail.com';


$from 'you@yourserver.com';


$message 'Hello';

$subject 'Test Mail';


mail($to$message$subject"From: $from""-f$from");


?> 
 

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 22 March 2012

Dynamic Menu Highlighting using php and CSS

The below example explains making a navigation menu that dynamically
highlights the currently displayed page using php and css

It is better to use a common navigation menu file on the site rather than repeating same code on all the pages.
The reason is that if the menu items change ,we can easily modified a single file rather than changing all the files.

In the navigation menu file (say navigationMenu.php) add the below code

   <div id="menu">
    <?php
    $active[$currentPage] = " class=active";                //dont forget to put space infront of class
    ?>
    <ul>
        <li <?php echo $active[1] ?>><a href="newfile1.php" id="index">HOME</a></li>
      <li <?php echo $active[2] ?>><a href="newfile2.php">CONTACT US</a></li>
        <li <?php echo $active[3] ?>><a href="newfile3.php">LINKS</a></li>
        <li <?php echo $active[4] ?>><a href="newfile4.php">TEAM</a></li>
    </ul>
   </div>

In the CSS add

#menu a:hover, #menu .active a  {
    background-color: red;
    color: #5A5A5A;
    display: normal;
    letter-spacing:1px;
    font-size: 11px;
  
}

In the individual pages (say contactus.php) add

<?php
$currentPage = 2;
include 'index.php';
?>

Demo : Clicking CONTACT US link



Wednesday 19 October 2011

How to calculate time difference in php

We can use time() function to calculate the difference between 2 dates in PHP. The time() function returns the current time as a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

The below function  returns the number of minutes, hours, days and months between 2 timestamp.


    /* 
     * Minutes  =  60       seconds
     * Hour     =  3600     seconds
     * Day      =  86400    seconds 

     * Month    =  2592000  seconds
     */


function timeAgo($time) {
   //get the time difference between current time and login time
   $timeDif=time()-$time;

   // month difference

   if (($timeDif/2592000)>=1) {
       if(floor(($timeDif/2592000))==1){
           return floor(($timeDif/2592000))." month";
       }
       else {
          return floor(($timeDif/2592000))." months";
       }
    }
    //day difference
    elseif (($timeDif/86400)>=1) {
      if(floor(($timeDif/86400)) == 1){
         return floor(($timeDif/86400))." day";
      }
      else{
         return floor(($timeDif/86400))." days";
       }
    }
    //hour difference
    elseif(($timeDif/3600)>=1) {
      if(floor(($timeDif/3600)) ==1){
         return floor(($timeDif/3600))." hour";
      }
      else{
         return floor(($timeDif/3600))." hours";
      }
    }
    // minute differnece
    elseif(($timeDif/60)>=1) {
      if(floor(($timeDif/60)) ==1){
         return floor(($timeDif/60))." minutes";
      }
      else{
         return floor(($timeDif/60))." minutes";
      }
    }else {
    return "less than 1 minute";
    }
}



Tuesday 18 October 2011

How to decrypt the md5 encrypted password in PHP

md5 is supposed to be a one way encryption. But we can validate the password. First create an md5 hash of the password supplied by the user, and compare that with the encrypted password in the database.

This example shows how to change the md5 encrypted password in the database 

     $username = $_POST['user']; // get the username from the  form

     $currentpassword = $_POST['password']; // get the current password from
                                                                           the form
 
     $newpassword = $_POST['newpassword']; // get the new password from the
                                                                              form
     $hash = md5($currentpassword); // encrypt the current password supplied
                                                            by the user

     $result = mysql_query("SELECT password from Users  where
     username='username' ");  // query the database for getting password for a
                                                   the user.

     $row = mysql_fetch_array($result);

     $p=$row[password]; // get the encrypted password from the database for the
                                           user
     if($p==$hash){

           $result = mysql_query("UPDATE members set       
                           password=md5('newpassword') where username='username' ");
      } // update the new password for the user in the database in encrypted form,
            only if the encrypted current password and the password stored in the
            database are same