Thursday 17 May 2012

Functions to validate user inputs with PHP

Validating user inputs in PHP is very important from the view of your application's security,  integrity and user experience. If you fail, your applications may be prone to serious security vulnerabilities such as XSS, SQL injection and so on.

First of all make sure you have GPC magic quotes enabled in your php.ini file.

Here are few functions that you can use in your PHP scripts to validate different inputs.

Validating an email address field
// This function will return true if $email is not a valid email address


function NotValidEmail($email) {
 if (preg_match("/^([._a-z0-9-]+[._a-z0-9-]*)@(([a-z0-9-]+\.)*([a-z0-9-]+)(\.[a-z]{2,3}))$/i", $email)) {
  return FALSE;
 }
 else {
  return TRUE;
 }
}


Validating a link
//returns true if $link is a valid looking link

function linkis_valid($link){
$link=strtolower($link);
if(preg_match("|http://[a-z_1-9\:\/\-\.]+|",$link, $array)){
return true;
}
return false;
}

Allowing only numbers
// returns only numbers from $text

function only_numbers($text){
$text=preg_replace("|[^0-9]|","",$text);
return $text;
}

Allowing only alphanumeric characters

// returns only alphanumeric characters from $text
function cleanalpha($text){
$text=preg_replace("|[^0-9a-zA-Z_\-\.]|","",$text);
return $text;
}





No comments:

Post a Comment