WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Mobile Dev World

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : Regex class - Provides a set of static methods to test users inputs, $_POSTs and $_GETs
Categories : PHP Classes, Utilities Click here to Update Your Picture
Carlo Tasca
Date : Feb 26th 2008
Grade : 5 of 5 (graded 1 times)
Viewed : 4465
File : 4768.zip
Images : No Images for this code example.
Search : More code by Carlo Tasca
Action : Grade This Code Example
Tools : My Examples List

 
Like this code?
Show the author your appreciation.
Submit your own code examples 
 

Class Regex contains a set of static methods that can be used to validate user inputs, $_POST and $_GET variables.

Most of the methods will return an integer. 0 if not valid, 1 otherwise.
Documentation and example of usage files are included in the zip file available to download.


<?php
include_once("Regex.class.php");
$num = 1.9;
echo
Regex::isValidInteger($num) . '<br />';
$num = 3;
echo
Regex::isValidInteger($num) . '<br />';
$num = 0;
echo
Regex::isValidInteger($num) . '<br />';
$num = 0;
echo
Regex::isValidIntegerNull($num) . '<br />';
$num = 3.3456567;
echo
Regex::isValidUsdFormat($num) . '<br />';
$num = 3.34;
echo
Regex::isValidUsdFormat($num) . '<br />';
$string = "";
echo
Regex::isValidString($string) . '<br />';
$string = "sdsaf";
echo
Regex::isValidString($string) . '<br />';
$string = "";
echo
Regex::isValidStringNull($string) . '<br />';
// the regex class has more methods you can use I have used just a few here
// All methods in the class are statics and most of them return 0 if not valid or 1 if valid.
// Here is the list of full methods available
/*
array checkGlobalGets ()
array checkGlobalPosts ()
int compareTo (string $aString, string $anOtherString)
int compareTwoStrings (string $aString, string $anOtherString)
int fullNameChecker ([string $aNameToCheck = ""])
void isGettingGlobalGET ()
void isGettingGlobalPOST ()
int isIllegalPassword ([string $aPasswordToCheck = ""])
int isIllegalUsername ([string $aUsernameToCheck = ""])
string isSidValid (string $s, [array $a = array()])
int isUsernameLegal ([string $aUsernameToCheck = ""])
int isValidDouble (double $aDouble)
int isValidEmailAddress ([string $aEmailToCheck = ""])
int isValidInteger (int $anInt)
int isValidIntegerNull (int $anInt)
int isValidString (string $aString)
int isValidStringAndDot (string $aString)
int isValidStringNull (string $aString)
int isValidUsdFormat (double $aDouble)
int isValidZeroPointFourDigitsDouble (double $aDouble)
int isValidZeroPointTwoDigitsDouble (double $aDouble)
mixed isVarCleanFrom (string $s, [array $a = array()])
array returnIllegalGETchars ()
array returnIllegalPOSTchars ()
array returnIllegalSIDchars ()
*/
?>




OUTPUT:
0
1
0
1
0
1
0
1
1




<?php
/**
* Class Regex
*
* @author Carlo Tasca
* @version 3.0
* @package util
*/
/**
* Provides a set of static methods to test users inputs, $_POSTs and $_GETs
*
*/
class Regex
{
   
/**
    * Class cannot be instantiated
    * Throws fatal error if trying to create Regex objects
    *
    */
   
private function __construct()
   {
     
trigger_error("Class Regex cannot be instantiated",E_USER_ERROR);
   }
   
/**
     * Return 1 if anInt is anInteger, 0 otherwise
     * 0 is not valid data
     *
     * @param int $anInt
     * @return int
     */
   
public static function isValidInteger ($anInt) {
     
$result = 0;
     
$ivi = "(^([1-9]{1})(([0-9]{1,10}))?)$";

      if (
ereg($ivi, $anInt)) {
         
$result = 1;
      }
      return (int)
$result;
   }

   
/**
     * Return 1 if anInt is anInteger, 0 otherwise
     * 0 is valid data
     *
     * @param int $anInt
     * @return int
     */
   
public static function isValidIntegerNull ($anInt) {
     
$result = 0;
     
$ivi = "(^([0-9]{1})(([0-9]{1,10}))?)$";

      if (
ereg($ivi, $anInt)) {
         
$result = 1;
      }
      return (int)
$result;
   }

   
/**
     * Return 1 if $aDouble is double/float, 0 otherwise
     * format must be 0.0000
     *
     * @param double $aDouble
     * @return int
     */
   
public static function isValidZeroPointFourDigitsDouble ($aDouble) {
     
$result = 0;
     
$ivd = "^(([0-9]{1,10})(\\.){1}$)([0-9]{1})([0-9]{1})([0-9]{1})([0-9]{1})$";

      if (
ereg($ivd, $aDouble)) {
         
$result = 1;
      }
      return (int)
$result;
   }

   
/**
     * Return 1 if $aDouble is double/float, 0 otherwise
     * format must be 0.00
     *
     * @param double $aDouble
     * @return int
     */
   
public static function isValidZeroPointTwoDigitsDouble ($aDouble) {
     
$result = 0;
     
$ivd = "^(0\\.)([0-9]{1})([0-9]{1})$";

      if (
ereg($ivd, $aDouble)) {
         
$result = 1;
      }
      return (int)
$result;
   }

   
/**
     * Return 1 if $aDouble is double/float, 0 otherwise
     * format must be 0.00 and can be 1.23 (max is 999.99)
     *
     * @param double $aDouble
     * @return int
     */
   
public static function isValidUsdFormat ($aDouble) {
     
$result = 0;
     
$ivusd = "^(([0-9]{1,9})(\\.)?)(([0-9]{0,1})([0-9]{0,1}))$";
      if (
eregi($ivusd, $aDouble)) {
         
$result = 1;
      }
      return (int)
$result;
   }

   
/**
     * Return 1 if $aDouble is double/float, 0 otherwise
     * format must be 0.00 and can be 1.23 or 1.2333 (max is 999.9999)
     *
     * @param double $aDouble
     * @return int
     */
   
public static function isValidDouble ($aDouble) {
     
$result = 0;
     
$ivusd = "^(([0-9]{1,9})(\\.)?)(([0-9]{0,1})([0-9]{0,1})(([0-9]{0,1})([0-9]{0,1})?))$";
      if (
eregi($ivusd, $aDouble)) {
         
$result = 1;
      }
      return (int)
$result;
   }
   
/**
     * Check a string between 1 and 150 chars
     *
     * @param string $aString
     * @return int
     */
   
public static function isValidString($aString)
   {
     
$result = 0;
     
$regEx = "^([[:alnum:]]){1,150}$";
      if (
ereg($regEx, $aString)) {
         
$result = 1;
      }
      return
$result;
   }
   
   
/**
     * Check a string between 1 and 150 chars
     *
     * @param string $aString
     * @return int
     */
   
public static function isValidStringNull($aString)
   {
     
$result = 0;
     
$regEx = "^([[:alnum:]]){0,150}$";
      if (
ereg($regEx, $aString)) {
         
$result = 1;
      }
      return
$result;
   }

   
/**
     * Check a string between 1 and 150 chars
     * . char is allowed
     *
     * @param string $aString
     * @return int
     */
   
public static function isValidStringAndDot($aString)
   {
     
$result = 0;
     
$regEx = "^([[:alnum:]]|.){1,150}$";
      if (
ereg($regEx, $aString)) {
         
$result = 1;
      }
      return
$result;
   }
   
/**
     * Returns 0 if username is less than 3 or more than 16 characters, 1 otherwise (legal)
     * Also must be a letter or a char number. No special chars allowed
     *
     * @param string $aUsernameToCheck
     * @return int
     */
   
public static function isUsernameLegal($aUsernameToCheck = "")
   {
     
$result = 0;
     
$regEx = "^[[:alnum:]]{3,16}$";
      if (
ereg($regEx, $aUsernameToCheck)) {
         
$result = 1;
      }
      return
$result;
   }
   
/**
     * Returns 0 if username is an illegal name, 1 otherwise (legal)
     *
     * @param string $aUsernameToCheck
     * @return int
     */

   
public static function isIllegalUsername($aUsernameToCheck = "")
   {
     
$result = 1;
     
$regEx = "^((root)|(bin)|(daemon)|(adm)|(lp)|(sync)|(shutdown)|
        (halt)|(mail)|(news)|(uucp)|(operator)|(games)|(mysql)|(httpd)|
        (nobody)|(dummy)|(www)|(cvs)|(shell)|(ftp)|(irc)|(debian)|(ns)|
        (download))$"
;

      if (
ereg($regEx, $aUsernameToCheck)) {
         
$result = 0;
      }
      return
$result;
   }
   
/**
     * Returns 0 if password contains illegal characters or less than 6 or more than 16,
     * 1 otherwise (legal)
     *
     * @param string $aPasswordToCheck
     * @return int
     */
   
public static function isIllegalPassword($aPasswordToCheck = "")
   {
     
$result = 0;
     
$regEx = "^[[:alnum:]]{6,16}$";
      if (
ereg($regEx, $aPasswordToCheck))
      {
         
$result = 1;
      }
      return
$result;
   }

   
/**
     * Returns 1 if a name is valid (between 2 and 10 chars)
     * Can contain - or '. Returns 0 otherwise
     *
     * @param string $aNameToCheck
     * @return int
     */
   
public static function fullNameChecker($aNameToCheck = "")
   {
     
$result = 0;
     
$regEx = "^([[:alpha:]]|-|'){2,10}$";
      if (
ereg($regEx, $aNameToCheck))
      {
         
$result = 1;
      }
      return
$result;
   }
   
/**
     * Checks whether email address is valid
     * Returns 1 if it is, 0 otherwise
     *
     * @param string $aEmailToCheck
     * @return int
     */
   
public static function isValidEmailAddress($aEmailToCheck = "")
   {
     
$result = 0;
     
$regEx = '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+' . '@' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$';
      if (
ereg($regEx, $aEmailToCheck)) {
         
$result = 1;
      }
      return
$result;
   }
   
/**
     * Compares two strings for equality
     * Must be same chars and be of same var type (string)
     * Returns 1 if valid, 0 otherwise
     *
     * @param string $aString
     * @param string $anOtherString
     * @return int
     */
   
public static function compareTo($aString, $anOtherString)
   {
     
$result = 0;
      if (
$aString === $anOtherString) {
         
$result = 1;
      }
      return
$result;
   }

   
/**
     * Compares two strings for equality (switched compared to compareTo())
     * Must be same chars and be of same var type (string)
     * Returns 0 if valid, 1 otherwise
     *
     * @param string $aString
     * @param string $anOtherString
     * @return int
     */
   
public static function compareTwoStrings($aString, $anOtherString)
   {
     
$result = 1;
      if (
$aString === $anOtherString) {
         
$result = 0;
      }
      return
$result;
   }
   
/**
    * Return string $ only and only if it doesnt contain any illegal characters
    * Characters to be made illegal should be defined in array $a
    * If illegal characters are found triggers a fatal error
    *
    * @param string $s string to check
    * @param array $a array of illegal characters
    * @return string or fatal error
    */
   
public static function isSidValid($s, $a = array())
   {

      foreach (
$a as $value)
      {
         if (
strchr($s, $value))
         {
           
$exception = "Session ID received contains illegal characters: ".$s;
           
trigger_error($exception ,E_USER_ERROR);
         }
      }
      return
$s;
   }

   
/**
    * Overloaded version of isSidValid
    * Return string $s only and only if it doesnt contain any illegal characters
    * Characters to be made illegal should be defined in array $a
    * If illegal characters are found returns false
    *
    * @param string $s string to check
    * @param array $a array of illegal characters
    * @return mixed
    */
   
public static function isVarCleanFrom($s, $a = array())
   {

      foreach (
$a as $value)
      {
         if (
strchr($s, $value))
         {
            return
false;
         }
      }
      return
$s;
   }
   
/**
    * Returns array of illegal characters for SIDs
    *
    * @return array
    */
   
public static function returnIllegalSIDchars()
   {
      return array(
"\"", "$", "#", "<", ">", "*", "(", ")", "{","}", "[", "]", ";", "~", "=");
   }
   
/**
    * Returns array of illegal characters for global variable $_GET
    *
    * @return array
    */
   
public static function returnIllegalGETchars()
   {
      return array(
"\"", "$", "<", ">", "*", "(", ")", "{","}", "[", "]", ";", "~", "=");
   }
   
/**
    * Returns array of illegal characters for global variable $_POST
    *
    * @return array
    */
   
public static function returnIllegalPOSTchars()
   {
      return array(
"\"", "$", "%","#", "<", ">", "*", "(", ")", "{","}", "[", "]", ";", "~", "=");
   }
   
/**
    * Checks variables posted via $_POST
    * Returns a $_POST[$key] value only if free from illegal characters defined
    * in returnIllegalPOSTchars() method
    *
    * @return array
    */
   
public static function checkGlobalPosts()
   {
      foreach (
$_POST as $key => $value)
      {
         
$_POST[$key] = Regex::isVarCleanFrom($value, Regex::returnIllegalPOSTchars());
      }
      return
$_POST;
   }
   
/**
    * Checks variables posted via $_GET
    * Returns a $_GET[$key] value only if free from illegal characters defined
    * in returnIllegalGETchars() method
    *
    * @return array
    */
   
public static function checkGlobalGets()
   {
      foreach (
$_GET as $key => $value)
      {
         
$_GET[$key] = Regex::isVarCleanFrom($value, Regex::returnIllegalGETchars());
      }
      return
$_GET;
   }
   
/**
    * Triggers a fatal error if a page receives $_POST variables
    * This method can be called within pages that do not require to receive $_POSTs
    * Just an extra layer of security
    *
    */
   
public static function isGettingGlobalPOST()
   {
      if (
count($_POST) > 0)
      {
         
trigger_error("File cannot receive posted data", E_USER_ERROR);
      }
   }   
   
/**
    * Triggers a fatal error if a page receives $_GET variables
    * This method can be called within pages that do not require to receive $_GETs
    * Just an extra layer of security
    *
    */
   
public static function isGettingGlobalGET()
   {
      if (
count($_GET) > 0)
      {
         
trigger_error("File cannot get data", E_USER_ERROR);
      }
   }
}
?>



Antispoof - a class to help prevent people hi-jacking and misusing parts of a website
Categories : PHP, PHP Classes, Security
Automatic Browsers Detect
Categories : PHP, PHP Classes, Headers, Browsers
Writing Portable MySQL Code in PHP: Porting to Oracle, Microsoft SQL Server, Sybase, Interbase, PostgreSQL and other databases using ADODB class library.
Categories : MySQL, PHP, PHP Classes, ODBC, General SQL
Convert SQL from oracle,mysql,mssql,sqlite and odbc to SQL compatible
Categories : PHP, PHP Classes, Databases, MySQL, MS SQL Server
Recordset Class for MSSQL database
Categories : PHP Classes, Databases, PHP, MS SQL Server
Powerful php/mysql Pagination for up to 6 URL Params
Categories : PHP, PHP Classes, Databases, MySQL, Navigation
How To Create a PDF Using PHP
Categories : PHP, PDF, PHP Classes, HTML and PHP
Simple Maiing list with newsletter support
Categories : PHP, PHP Classes, Mail
Freshmeat.net XML-RPC - This class is meant to query Freshmeat for information about registered projects.
Categories : PHP, PHP Classes, XML, Web Services
cPanel Subdomains Creator - Create cPanel subdomains without logging into cPanel. Let your visitors create their own subdomains without your intervention. Moreover, it will inform if a subdomain is already exists.
Categories : PHP, Web Services, PHP Classes
Objects to XML Serializer/Unserializer
Categories : PHP, PHP Classes, DOM XML, Serialize
Simple Mini Poll class library (SimPoll)
Categories : PHP, PHP Classes, Databases, MySQL, Complete Programs
RSS parser. Parses RSS into an array. Quick and nasty but does the job. No checking is done for correct Tags, only correct XML. PHP4 needed to display result (uses print_r).
Categories : PHP, XML, PHP Classes, Rich Site Summary (RSS)
EasyPhpThumbnail Class - The EasyPhpThumbnail class allows you to generate thumbnails and handle image manipulation for GIF, JPG and PNG on-the-fly.
Categories : PHP, PHP Classes, Object Oriented, Graphics, GD image library
Blueshoes PHP Application Framework
Categories : PHP, Frameworks, PHP Classes