Advertisement
amereservant

24 PHP Form Validation Snippets/Functions

Jul 15th, 2011
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 10.71 KB | None | 0 0
  1.  
  2. <?php
  3. /**
  4.  * 24 Form Validation Snippets
  5.  *
  6.  * This is a group of snippets from {@link http://hungred.com/useful-information/php-form-validation-snippets/}
  7.  * that provide useful ways to validate form data.
  8.  *
  9.  * This file CANNOT be used as-is because of the duplicate function names.
  10.  * They are meant to illustrate different ways of accomplishing the same thing and
  11.  * show alternative/better methods for some functions.
  12.  *
  13.  * Beyond validation, I highly recommend using PHP's PDO class and the bindParam() method
  14.  * that provides additional SQL Injection prevention.
  15.  */
  16.  
  17. /**
  18.  * Validate Email
  19.  * We can perform an email validation through this function.
  20.  */
  21. function isValidEmail($email){
  22.     return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i', $email);
  23. }
  24. // PHP 5.2 and above.
  25. function fnValidateEmail($email){
  26.     return filter_var($email, FILTER_VALIDATE_EMAIL);
  27. }
  28.  
  29. /**
  30.  * Sanitize Email
  31.  * We can further sanitize our email to ensure that everything is alright.
  32.  */
  33. function fnSanitizeEmaill($string){
  34.     return preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i' , '', $string );
  35. }
  36. // PHP 5.2 and above.
  37. function fnSanitizeEmaill($url){
  38.     return filter_var($url, FILTER_SANITIZE_EMAIL);
  39. }
  40.  
  41. /**
  42.  * Validate Email Exist
  43.  * This is not possible but certain validation can be use to validate email existence.
  44.  * NOTE: This function uses eregi, which is DEPRECATED as of PHP 5.3.
  45.  */
  46. function check_email($email){
  47.     $email_error = false;
  48.     $Email = htmlspecialchars(stripslashes(strip_tags(trim($email)))); //parse unnecessary characters to prevent exploits
  49.     if ($Email == '') { email_error = true; }
  50.     elseif (!eregi('^([a-zA-Z0-9._-])+@([a-zA-Z0-9._-])+\.([a-zA-Z0-9._-])([a-zA-Z0-9._-])+', $Email)) { email_error = true; }
  51.     else {
  52.     list($Email, $domain) = split('@', $Email, 2);
  53.         if (! checkdnsrr($domain, 'MX')) { email_error = true; }
  54.         else {
  55.             $array = array($Email, $domain);
  56.             $Email = implode('@', $array);
  57.         }
  58.     }
  59.     if (email_error) { return false; } else{return true;}
  60. }
  61.  
  62. /**
  63.  * Validate Number Only
  64.  * We can use PHP built-in function to validate whether a given value is a number.
  65.  */
  66. function fnValidateNumber($value){
  67.     #is_ double($value);
  68.    #is_ float($value);
  69.    #is_ int($value);
  70.    #is_ integer($value);
  71.    return is_numeric($value);
  72. }
  73. // PHP 5.2 and above.
  74. function fnValidateNumber($value){
  75.     #return filter_var($value, FILTER_VALIDATE_FLOAT); // float
  76.    return filter_var($value, FILTER_VALIDATE_INT); # int
  77. }
  78.  
  79. /**
  80.  * Sanitize Number
  81.  * We can force all value to be only numeric by sanitize them.
  82.  */
  83. function fnSanitizeNumber($str){
  84.     #letters and space only
  85.    return preg_match('/[^0-9]/', '', $str);
  86. }
  87. //PHP 5.2 and above.
  88. function fnSanitizeNumber($value){
  89.     #return filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT); // float
  90.    return filter_var($value, FILTER_SANITIZE_NUMBER_INT); # int
  91. }
  92.  
  93. /**
  94.  * Validate String Only
  95.  * Sometimes to validate name we can use this function to restrict only letters and spaces.
  96.  */
  97. function fnValidateStringr($str){
  98.     #letters and space only
  99.    return preg_match('/^[A-Za-z\s ]+$/', $str);
  100. }
  101.  
  102. /**
  103.  * Sanitize String
  104.  * We can sanitize it instead of validate user input.
  105.  */
  106. function fnSanitizeStringr($str){
  107.     #letters and space only
  108.    return preg_replace('/[^A-Za-z\s ]/', '', $str);
  109. }
  110. // PHP 5.2 and above. built-in function by PHP provides a much more powerful sanitize capability.
  111. function fnSanitizeStringr($str){
  112.     return filter_var($str, FILTER_SANITIZE_STRIPPED); # only 'String' is allowed eg. '<br>HELLO</br>' => 'HELLO'
  113. }
  114.  
  115. /**
  116.  * Validate Alphanumeric Characters
  117.  * This validates alphanumeric characters.
  118.  */
  119. function fnValidateAlphanumeric($string){
  120.     return ctype_alnum($string);
  121. }
  122.  
  123. /**
  124.  * Sanitize Alphanumeric Characters
  125.  * This sanitize alphanumeric characters. eg. “HELLO! Do we have 90 idiots running
  126.  * around here?” => “HELLO Do we have 90 idiots running around here”
  127.  */
  128. function fnSanitizeAlphanumeric($string){
  129.     return preg_replace('/[^a-zA-Z0-9]/', '', $string);
  130. }
  131.  
  132. /**
  133.  * Validate URL Exist
  134.  * This function will check whether a given URL exist and not only validate it.
  135.  */
  136. function url_exist($url){
  137.     $url = @parse_url($url);
  138.     if (!$url)
  139.     {
  140.         return false;
  141.     }
  142.     $url = array_map('trim', $url);
  143.     $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
  144.     $path = (isset($url['path'])) ? $url['path'] : '';
  145.     if ($path == '')
  146.     {
  147.         $path = '/';
  148.     }
  149.     $path .= (isset($url['query'])) ? '?$url[query]' : '';
  150.     if (isset($url['host']) AND $url['host'] != @gethostbyname($url['host']))
  151.     {
  152.         if (PHP_VERSION >= 5)
  153.         {
  154.             $headers = @get_headers('$url[scheme]://$url[host]:$url[port]$path');
  155.         }
  156.         else
  157.         {
  158.             $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
  159.             if (!$fp)
  160.             {
  161.                 return false;
  162.             }
  163.             fputs($fp, 'HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n');
  164.             $headers = fread($fp, 4096);
  165.             fclose($fp);
  166.         }
  167.         $headers = (is_array($headers)) ? implode('\n', $headers) : $headers;
  168.         return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
  169.     }
  170.     return false;
  171. }
  172.  
  173. /**
  174.  * Validate URL Format
  175.  * This function will validate a given url to ensure the format is correct.
  176.  */
  177. function fnValidateUrl($url){
  178.     return preg_match('/^(http(s?):\/\/|ftp:\/\/{1})((\w+\.){1,})\w{2,}$/i', $url);
  179. }
  180. // PHP 5.2 and above.
  181. function fnValidateUrl($url){
  182.     return filter_var($url, FILTER_VALIDATE_URL);
  183. }
  184.  
  185. /**
  186.  * Sanitize URL
  187.  * PHP 5.2 and above.
  188. function fnSanitizeUrl($url){
  189.  
  190.     return filter_var($url, FILTER_SANITIZE_URL);
  191. }
  192.  
  193. /**
  194.  * Validate Image Exist
  195.  * This function will check whether a given image link exist and not only validate it.
  196.  */
  197. function image_exist($url) {
  198.     if(@file_get_contents($url,0,NULL,0,1)){return 1;}else{ return 0;}
  199. }
  200.  
  201. /**
  202.  * Validate IP Address
  203.  * This function will validate an IP address.
  204.  */
  205. function fnValidateIP($IP){
  206.     return preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP)
  207. }
  208. //PHP 5 and above. This can also specific validation for IPV4 or IPV6.
  209. function fnValidateIP($ip){
  210.     return filter_var($ip, FILTER_VALIDATE_IP);
  211. }
  212.  
  213. /**
  214.  * Validate Proxy
  215.  * This function will let us detect proxy visitors even those that are behind anonymous proxy.
  216.  */
  217. function fnValidateProxy(){
  218.     if ($_SERVER['HTTP_X_FORWARDED_FOR']
  219.        || $_SERVER['HTTP_X_FORWARDED']
  220.        || $_SERVER['HTTP_FORWARDED_FOR']
  221.        || $_SERVER['HTTP_VIA']
  222.        || in_array($_SERVER['REMOTE_PORT'], array(8080,80,6588,8000,3128,553,554))
  223.        || @fsockopen($_SERVER['REMOTE_ADDR'], 80, $errno, $errstr, 30))
  224.     {
  225.         exit('Proxy detected');
  226.     }
  227. }
  228.  
  229. /**
  230.  * Validate Username
  231.  * Before we validate whether a given username is matches the one in our database, we can
  232.  * perform a validation check first to prevent any unnecessary SQL call.
  233.  */
  234. function fnValidateUsername($username){
  235.     #alphabet, digit, @, _ and . are allow. Minimum 6 character. Maximum 50 characters (email address may be more)
  236.    return preg_match('/^[a-zA-Z\d_@.]{6,50}$/i', $username);
  237. }
  238.  
  239. /**
  240.  * Validate Strong Password
  241.  * Another good thing is to validate whether a particular password given by the user is
  242.  * strong enough. You can do that using this function which required the password to have
  243.  * a minimum of 8 characters, at least 1 uppercase, 1 lowercase and 1 number.
  244.  */
  245. function fnValidatePassword($password){
  246.     #must contain 8 characters, 1 uppercase, 1 lowercase and 1 number
  247.    return preg_match('/^(?=^.{8,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$/', $password);
  248. }
  249.  
  250. /**
  251.  * Validate US Phone Number
  252.  * This function will validate US phone number for US users.
  253.  */
  254. function fnValidateUSPhone($phoneNo){
  255.     return preg_match('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x', $phoneNo);
  256. }
  257.  
  258. /**
  259.  * Validate US Postal Code
  260.  * This function validate US postal code.
  261.  */
  262. function fnValidateUSPostal($postalcode){
  263.     #eg. 92345-3214
  264.    return preg_match('/^([0-9]{5})(-[0-9]{4})?$/i',$postalcode);
  265. }
  266.  
  267. /**
  268.  * Validate US Social Security Numbers
  269.  * This function validate US Social Security Numbers.
  270.  */
  271. function fnValidateUSSocialSecurityCode($ssb){
  272.     #eg. 531-63-5334
  273.    return preg_match('/^[\d]{3}-[\d]{2}-[\d]{4}$/',$ssn);
  274. }
  275.  
  276. /**
  277.  * Validate Credit Card
  278.  * This function validate credit card format.
  279.  */
  280. function fnValidateCreditCard($cc){
  281.     #eg. 718486746312031
  282.    return preg_match('/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/', $cc);
  283. }
  284.  
  285. /**
  286.  * Validate Date
  287.  * This is a date format MM-DD-YYYY or MM-DD-YY validation which validate from year 0000-9999.
  288.  */
  289. function fnValidateDate($date){
  290.     #05/12/2109
  291.    #05-12-0009
  292.    #05.12.9909
  293.    #05.12.99
  294.    return preg_match('/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.][0-9]?[0-9]?[0-9]{2})*$/', $date);
  295. }
  296. // This is a date format YYYY-DD-MM or YY-MM-DD validation which validate from year 0000-9999.
  297. function fnValidateDate($date){
  298.     #2009/12/11
  299.    #2009-12-11
  300.    #2009.12.11
  301.    #09.12.11
  302.    return preg_match('#^([0-9]?[0-9]?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01]))*$#', $date);
  303. }
  304.  
  305. /**
  306.  * Validate Hexadecimal Colors
  307.  * This is a good validation for people who allows their user to change color in their system.
  308.  */
  309. function fnValidateColor($color){
  310.     #CCC
  311.    #CCCCC
  312.    #FFFFF
  313.    return preg_match('/^#(?:(?:[a-f0-9]{3}){1,2})$/i', $color);
  314. }
  315.  
  316. /**
  317.  * Make Query Safe
  318.  * This function help sanitize our data to be SQL injection safe.
  319.  */
  320. function _clean($str){
  321.     return is_array($str) ? array_map('_clean', $str) : str_replace('\\', '\\\\', htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES));
  322. }
  323. //usage call it somewhere in beginning of your script
  324. _clean($_POST);
  325. _clean($_GET);
  326. _clean($_REQUEST);// and so on..
  327.  
  328. /**
  329.  * Make Data Safe
  330.  * This function help to keep us protected against XSS, JS and SQL injection by removing tags.
  331.  */
  332. function _clean($str){
  333.     return is_array($str) ? array_map('_clean', $str) : str_replace('\\', '\\\\', strip_tags(trim(htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES))));
  334. }
  335. //usage call it somewhere in beginning of your script
  336. _clean($_POST);
  337. _clean($_GET);
  338. _clean($_REQUEST);// and so on..
  339.  
  340.  
  341. /**
  342.  * Summary
  343.  * A paranoid way to perform a form validation would be to validate first then sanitize
  344.  * your values for precautions.
  345.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement