{"id":13,"date":"2010-08-10T12:59:19","date_gmt":"2010-08-10T11:59:19","guid":{"rendered":"http:\/\/blogs.silicontechnix.com\/?p=13"},"modified":"2010-08-11T09:17:07","modified_gmt":"2010-08-11T08:17:07","slug":"php-validations","status":"publish","type":"post","link":"https:\/\/blogs.silicontechnix.com\/?p=13","title":{"rendered":"PHP Validations"},"content":{"rendered":"<h2>Validate Email<\/h2>\n<p>We can perform an email validation through this function.<\/p>\n<pre class=\"brush: php;\">\tfunction isValidEmail($email){\r\n\t\treturn eregi('^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$', $email);\r\n\t}\r\n<\/pre>\n<p>After fainted for a few seconds when i saw unreal4u finding, i decided to throw up preg_match solution instead.<\/p>\n<pre class=\"brush: php;\">\tfunction isValidEmail($email){\r\n\t\treturn preg_match('\/^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$\/i', $email);\r\n\t}\r\n<\/pre>\n<p>PHP 5.2 and above.<\/p>\n<pre class=\"brush: php;\">function fnValidateEmail($email)\r\n{\r\n  return filter_var($email, FILTER_VALIDATE_EMAIL);\r\n}\r\n<\/pre>\n<h2>Sanitize Email<\/h2>\n<p>We can further sanitize our email to ensure that everything is alright.<\/p>\n<pre class=\"brush: php;\">function fnSanitizeEmaill($string) {\r\n     return  preg_replace( '((?:\\n|\\r|\\t|%0A|%0D|%08|%09)+)i' , '', $string );\r\n}\r\n<\/pre>\n<p>PHP 5.2 and above.<\/p>\n<pre class=\"brush: php;\">function fnSanitizeEmaill($url)\r\n{\r\n  return filter_var($url, FILTER_SANITIZE_EMAIL);\r\n}\r\n<\/pre>\n<h2>Validate Email Exist<\/h2>\n<p>This is not possible but certain validation can be use to <a href=\"http:\/\/hungred.com\/how-to\/php-check-remote-email-url-image-link-exist\/\">validate email existence<\/a>.<\/p>\n<pre class=\"brush: php;\">function check_email($email)\r\n{\r\n\t$email_error = false;\r\n\t$Email = htmlspecialchars(stripslashes(strip_tags(trim($email)))); \/\/parse unnecessary characters to prevent exploits\r\n\tif ($Email == '') { email_error = true; }\r\n\telseif (!eregi('^([a-zA-Z0-9._-])+@([a-zA-Z0-9._-])+\\.([a-zA-Z0-9._-])([a-zA-Z0-9._-])+', $Email)) { email_error = true; }\r\n\telse {\r\n\tlist($Email, $domain) = split('@', $Email, 2);\r\n\t\tif (! checkdnsrr($domain, 'MX')) { email_error = true; }\r\n\t\telse {\r\n\t\t$array = array($Email, $domain);\r\n\t\t$Email = implode('@', $array);\r\n\t\t}\r\n\t}\r\n\r\n\tif (email_error) { return false; } else{return true;}\r\n}\r\n<\/pre>\n<h2>Validate Number Only<\/h2>\n<p>We can use PHP built-in function to validate whether a given value is a number.<\/p>\n<pre class=\"brush: php;\">function fnValidateNumber($value)\r\n{\r\n\t#is_ double($value);\r\n\t#is_ float($value);\r\n\t#is_ int($value);\r\n\t#is_ integer($value);\r\n\treturn is_numeric($value);\r\n}\r\n<\/pre>\n<p>PHP 5.2 and above.<\/p>\n<pre class=\"brush: php;\">function fnValidateNumber($value)\r\n{\r\n\t#return filter_var($value, FILTER_VALIDATE_FLOAT); \/\/ float\r\n\treturn filter_var($value, FILTER_VALIDATE_INT); # int\r\n}\r\n<\/pre>\n<h2>Sanitize Number<\/h2>\n<p>We can force all value to be only numeric by sanitize them.<\/p>\n<pre class=\"brush: php;\">function fnSanitizeNumber($str)\r\n{\r\n\t#letters and space only\r\n\treturn preg_match('\/[^0-9]\/', '', $str);\r\n}\r\n<\/pre>\n<p>PHP 5.2 and above.<\/p>\n<pre class=\"brush: php;\">function fnSanitizeNumber($value)\r\n{\r\n\t#return filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT); \/\/ float\r\n\treturn filter_var($value, FILTER_SANITIZE_NUMBER_INT); # int\r\n}\r\n<\/pre>\n<h2>Validate String Only<\/h2>\n<p>Sometimes to validate name we can use this function to restrict only letters and spaces.<\/p>\n<pre class=\"brush: php;\">function fnValidateStringr($str)\r\n{\r\n\t#letters and space only\r\n\treturn preg_match('\/^[A-Za-z\\s ]+$\/', $str);\r\n}\r\n<\/pre>\n<h2>Sanitize String<\/h2>\n<p>We can sanitize it instead of validate user input.<\/p>\n<pre class=\"brush: php;\">function fnSanitizeStringr($str)\r\n{\r\n\t#letters and space only\r\n\treturn preg_replace('\/[^A-Za-z\\s ]\/', '', $str);\r\n}\r\n<\/pre>\n<p>PHP 5.2 and above. built-in function by PHP provides a much more powerful sanitize capability.<\/p>\n<pre class=\"brush: php;\">function fnSanitizeStringr($str)\r\n{\r\n\treturn filter_var($str, FILTER_SANITIZE_STRIPPED); # only 'String' is allowed eg. '&lt;br&gt;HELLO&lt;\/br&gt;' =&gt; 'HELLO'\r\n}\r\n<\/pre>\n<h2>Validate Alphanumeric Characters<\/h2>\n<p>This validates alphanumeric characters.<\/p>\n<pre class=\"brush: php;\">function fnValidateAlphanumeric($string)\r\n{\r\n\treturn ctype_alnum ($string);\r\n}\r\n<\/pre>\n<h2>Sanitize Alphanumeric Characters<\/h2>\n<p>This sanitize alphanumeric characters. eg. \u201cHELLO! Do we have 90 idiots running around here?\u201d =&gt; \u201cHELLO Do we have 90 idiots running around here\u201d<\/p>\n<pre class=\"brush: php;\">function fnSanitizeAlphanumeric($string)\r\n{\r\n\treturn preg_replace('\/[^a-zA-Z0-9]\/', '', $string);\r\n}\r\n<\/pre>\n<h2>Validate URL Exist<\/h2>\n<p>This <a href=\"http:\/\/hungred.com\/how-to\/php-check-remote-email-url-image-link-exist\/\">function<\/a> will check whether a given URL exist and not only validate it.<\/p>\n<pre class=\"brush: php;\">\tfunction url_exist($url)\r\n\t{\r\n\t\t$url = @parse_url($url);\r\n\r\n\t\tif (!$url)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t$url = array_map('trim', $url);\r\n\t\t$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];\r\n\t\t$path = (isset($url['path'])) ? $url['path'] : '';\r\n\r\n\t\tif ($path == '')\r\n\t\t{\r\n\t\t\t$path = '\/';\r\n\t\t}\r\n\r\n\t\t$path .= (isset($url['query'])) ? '?$url[query]' : '';\r\n\r\n\t\tif (isset($url['host']) AND $url['host'] != @gethostbyname($url['host']))\r\n\t\t{\r\n\t\t\tif (PHP_VERSION &gt;= 5)\r\n\t\t\t{\r\n\t\t\t\t$headers = @get_headers('$url[scheme]:\/\/$url[host]:$url[port]$path');\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);\r\n\r\n\t\t\t\tif (!$fp)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t\tfputs($fp, 'HEAD $path HTTP\/1.1\\r\\nHost: $url[host]\\r\\n\\r\\n');\r\n\t\t\t\t$headers = fread($fp, 4096);\r\n\t\t\t\tfclose($fp);\r\n\t\t\t}\r\n\t\t\t$headers = (is_array($headers)) ? implode('\\n', $headers) : $headers;\r\n\t\t\treturn (bool)preg_match('#^HTTP\/.*\\s+[(200|301|302)]+\\s#i', $headers);\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n<\/pre>\n<h2>Validate URL Format<\/h2>\n<p>This function will validate a given url to ensure the format is correct.<\/p>\n<pre class=\"brush: php;\">function fnValidateUrl($url){\r\nreturn preg_match('\/^(http(s?):\\\/\\\/|ftp:\\\/\\\/{1})((\\w+\\.){1,})\\w{2,}$\/i', $url);\r\n}\r\n<\/pre>\n<p>PHP 5.2 and above.<\/p>\n<pre class=\"brush: php;\">function fnValidateUrl($url)\r\n{\r\n  return filter_var($url, FILTER_VALIDATE_URL);\r\n}\r\n<\/pre>\n<h2>Sanitize URL<\/h2>\n<p>PHP 5.2 and above.<\/p>\n<pre class=\"brush: php;\">function fnSanitizeUrl($url)\r\n{\r\n  return filter_var($url, FILTER_SANITIZE_URL);\r\n}\r\n<\/pre>\n<h2>Validate Image Exist<\/h2>\n<p>This <a href=\"http:\/\/hungred.com\/how-to\/php-check-remote-email-url-image-link-exist\/\">function<\/a> will check whether a given image link exist and not only validate it.<\/p>\n<pre class=\"brush: php;\">\tfunction image_exist($url) {\r\n\tif(@file_get_contents($url,0,NULL,0,1)){return 1;}else{ return 0;}\r\n\t}\r\n<\/pre>\n<h2>Validate IP Address<\/h2>\n<p>This function will validate an IP address.<\/p>\n<pre class=\"brush: php;\">function fnValidateIP($IP){\r\n\treturn 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)\r\n}\r\n<\/pre>\n<p>PHP 5 and above. This can also specific validation for IPV4 or IPV6.<\/p>\n<pre class=\"brush: php;\">function fnValidateIP($ip)\r\n{\r\n  return filter_var($ip, FILTER_VALIDATE_IP);\r\n}\r\n<\/pre>\n<h2>Validate Proxy<\/h2>\n<p>This function will let us detect proxy visitors even those that are behind anonymous proxy.<\/p>\n<pre class=\"brush: php;\">function fnValidateProxy(){\r\n\tif ($_SERVER['HTTP_X_FORWARDED_FOR']\r\n\t   || $_SERVER['HTTP_X_FORWARDED']\r\n\t   || $_SERVER['HTTP_FORWARDED_FOR']\r\n\t   || $_SERVER['HTTP_VIA']\r\n\t   || in_array($_SERVER['REMOTE_PORT'], array(8080,80,6588,8000,3128,553,554))\r\n\t   || @fsockopen($_SERVER['REMOTE_ADDR'], 80, $errno, $errstr, 30))\r\n\t{\r\n\t\texit('Proxy detected');\r\n\t}\r\n}\r\n<\/pre>\n<h2>Validate Username<\/h2>\n<p>Before we validate whether a given username is matches the one in our database, we can perform a validation check first to prevent any unnecessary SQL call.<\/p>\n<pre class=\"brush: php;\">function fnValidateUsername($username){\r\n\t#alphabet, digit, @, _ and . are allow. Minimum 6 character. Maximum 50 characters (email address may be more)\r\n\treturn preg_match('\/^[a-zA-Z\\d_@.]{6,50}$\/i', $username);\r\n}\r\n<\/pre>\n<h2>Validate Strong Password<\/h2>\n<p>Another good thing is to validate whether a particular password given by the user is strong enough. You can do that using this function which required the password to have a minimum of 8 characters, at least 1 uppercase, 1 lowercase and 1 number.<\/p>\n<pre class=\"brush: php;\">function fnValidatePassword($password){\r\n\t#must contain 8 characters, 1 uppercase, 1 lowercase and 1 number\r\n\treturn preg_match('\/^(?=^.{8,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$\/', $password);\r\n}\r\n<\/pre>\n<h2>Validate US Phone Number<\/h2>\n<p>This function will validate US phone number for US users.<\/p>\n<pre class=\"brush: php;\">function fnValidateUSPhone($phoneNo){\r\n\treturn preg_match('\/\\(?\\d{3}\\)?[-\\s.]?\\d{3}[-\\s.]\\d{4}\/x', $phoneNo);\r\n}\r\n<\/pre>\n<h2>Validate US Postal Code<\/h2>\n<p>This function validate US postal code.<\/p>\n<pre class=\"brush: php;\">function fnValidateUSPostal($postalcode){\r\n\t#eg. 92345-3214\r\n\treturn preg_match('\/^([0-9]{5})(-[0-9]{4})?$\/i',$postalcode);\r\n}\r\n<\/pre>\n<h2>Validate US Social Security Numbers<\/h2>\n<p>This function validate US Social Security Numbers.<\/p>\n<pre class=\"brush: php;\">function fnValidateUSSocialSecurityCode($ssb){\r\n\t#eg. 531-63-5334\r\n\treturn preg_match('\/^[\\d]{3}-[\\d]{2}-[\\d]{4}$\/',$ssn);\r\n}\r\n<\/pre>\n<h2>Validate Credit Card<\/h2>\n<p>This function validate credit card format.<\/p>\n<pre class=\"brush: php;\">function fnValidateCreditCard($cc){\r\n\t#eg. 718486746312031\r\n\treturn 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);\r\n}\r\n<\/pre>\n<h2>Validate Date<\/h2>\n<p>This is a date format MM-DD-YYYY or MM-DD-YY validation which validate from year 0000-9999.<\/p>\n<pre class=\"brush: php;\">function fnValidateDate($date){\r\n\t#05\/12\/2109\r\n\t#05-12-0009\r\n\t#05.12.9909\r\n\t#05.12.99\r\n\treturn preg_match('\/^((0?[1-9]|1[012])[- \/.](0?[1-9]|[12][0-9]|3[01])[- \/.][0-9]?[0-9]?[0-9]{2})*$\/', $date);\r\n}\r\n<\/pre>\n<p>This is a date format YYYY-DD-MM or YY-MM-DD validation which validate from year 0000-9999.<\/p>\n<pre class=\"brush: php;\">function fnValidateDate($date){\r\n\t#2009\/12\/11\r\n\t#2009-12-11\r\n\t#2009.12.11\r\n\t#09.12.11\r\n\treturn preg_match('#^([0-9]?[0-9]?[0-9]{2}[- \/.](0?[1-9]|1[012])[- \/.](0?[1-9]|[12][0-9]|3[01]))*$#'', $date);\r\n}\r\n<\/pre>\n<h2>Validate Hexadecimal Colors<\/h2>\n<p>This is a good validation for people who allows their user to change color in their system.<\/p>\n<pre class=\"brush: php;\">function fnValidateColor($color){\r\n\t#CCC\r\n\t#CCCCC\r\n\t#FFFFF\r\n\treturn preg_match('\/^#(?:(?:[a-f0-9]{3}){1,2})$\/i', $color);\r\n}\r\n<\/pre>\n<h2>Make Query Safe<\/h2>\n<p>This function help sanitize our data to be SQL injection safe.<\/p>\n<pre class=\"brush: php;\">function _clean($str){\r\nreturn is_array($str) ? array_map('_clean', $str) : str_replace('\\\\', '\\\\\\\\', htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES));\r\n}\r\n\r\n\/\/usage call it somewhere in beginning of your script\r\n_clean($_POST);\r\n_clean($_GET);\r\n_clean($_REQUEST);\/\/ and so on..\r\n<\/pre>\n<h2>Make Data Safe<\/h2>\n<p>This function help to keep us protected against XSS, JS and SQL injection by removing tags.<\/p>\n<pre class=\"brush: php;\">function _clean($str){\r\nreturn is_array($str) ? array_map('_clean', $str) : str_replace('\\\\', '\\\\\\\\', strip_tags(trim(htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES))));\r\n}\r\n\r\n\/\/usage call it somewhere in beginning of your script\r\n_clean($_POST);\r\n_clean($_GET);\r\n_clean($_REQUEST);\/\/ and so on..\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Validate Email We can perform an email validation through this function. function isValidEmail($email){ return eregi(&#8216;^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$&#8217;, $email); } After fainted for a few seconds when i saw unreal4u finding, i decided to throw up preg_match solution instead. function isValidEmail($email){ return preg_match(&#8216;\/^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$\/i&#8217;, $email); } PHP 5.2 and above. function fnValidateEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL); } Sanitize Email [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_s2mail":"","jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[12],"tags":[11,8,478,10],"class_list":["post-13","post","type-post","status-publish","format-standard","hentry","category-programming","tag-functions","tag-php","tag-programming","tag-validation"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p12j6H-d","_links":{"self":[{"href":"https:\/\/blogs.silicontechnix.com\/index.php?rest_route=\/wp\/v2\/posts\/13","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blogs.silicontechnix.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.silicontechnix.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.silicontechnix.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.silicontechnix.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=13"}],"version-history":[{"count":8,"href":"https:\/\/blogs.silicontechnix.com\/index.php?rest_route=\/wp\/v2\/posts\/13\/revisions"}],"predecessor-version":[{"id":34,"href":"https:\/\/blogs.silicontechnix.com\/index.php?rest_route=\/wp\/v2\/posts\/13\/revisions\/34"}],"wp:attachment":[{"href":"https:\/\/blogs.silicontechnix.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=13"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.silicontechnix.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=13"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.silicontechnix.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=13"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}