Tuesday, 15 October 2013

Function to Avoid SQL Injection

function clean_input($input)
{
   $input = trim($input);
   
   //check to see if magic quotes are turned on
   if(get_magic_quotes_gpc())
   {   
   $input = stripslashes($input);
   }
   
   //check for numeric values, if not
   //clean it
   if(!is_numeric($input))
   {
  $input = mysql_escape_string($input);
   }
   return($input);
} 

Function to avoid XSS (Cross Site Scripting)

function test_input($data)
{
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}


Function To Avoid Email Injection

function spamcheck($field)
  {
  //filter_var() sanitizes the e-mail
  //address using FILTER_SANITIZE_EMAIL
  $field=filter_var($field, FILTER_SANITIZE_EMAIL);

  //filter_var() validates the e-mail
  //address using FILTER_VALIDATE_EMAIL
  if(filter_var($field, FILTER_VALIDATE_EMAIL))
    {
    return TRUE;
    }
  else
    {
    return FALSE;
    }
  }



In the code above we use PHP filters to validate input:
  • The FILTER_SANITIZE_EMAIL filter removes all illegal e-mail characters from a string
  • The FILTER_VALIDATE_EMAIL filter validates value as an e-mail address

String Functions

How to find the length of string ?
strlen() function counts the number of characters including white spaces.
<?php
echo strlen("Hello world!"); // output : 12
?>

How to remove white space from the string?
trim() function removes white spaces from start and end of string.
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str," Hello"); // output : Hello 
?>