www.www.zaachi.com »  My Blog/Php  »  Simple check variables

Simple check variables



The forms are practically simplest method how to get dates from user. This simplicity have connection with danger of this dates. We can’t believe to users and so it is necessary all this inputs make safe and check dates. It is not enough e.g. write, that in this input user must write valid email, because always exists somebody, who writes random string and not valid email. Badly checked input can lead to errors as SQL injection or XSS attack. <br /><br />
Such form is component of almost every Web and if you are bored with making check of each such form, you may make few so simple functions, which will care about checking. It can’t be only forms, but also about checking of variables in scripts. In this example we will make class, which will have each method to care about check of different value in.

 

String length control
int check_length( mixed $var, int $min, int $max );

We will begin with something more simple, and that with method pro string length checking. Input values are three: controlled string, minimal length of string and maximal length of string. Minimal length we could give as unnecessary parameter, which will have default value 0, but this is your option.

In this method we won’t control only length of string, but it will enable check of array too. This solve two problems:

function check_length( $var, $min, $max ){
    if( !is_int( $min ) || !is_int( $max ) )
        return 0;
        
    switch( gettype( $var ) ){
        case 'string' : {
            return ( strlen( trim( $var ) ) < $min || strlen( trim( $var ) ) > $max ? 0 : 1 );
            //break;   
        }
        case 'array' : {
            //recursive count
            $count = count( $var, COUNT_RECURSIVE );
            return ( $count < $min || $count > $max ? 0 : 1 );
            //break;
        }
        default: return 0;   
    }  
}

This method returns one or zero, according to result of control.

Date control
int check_date( string $date [, string $splitting ]);

Another method, which we will look on and which will be also used often, is date control. Date is mostly entered in form YEAR-MONTH-DAY. This input will be presumed by our method and so entered date will be one of input values. Second parameter will be splitting char, which is used in date. Method firstly, with function ”explode”, split date to his parts and then checks validity of date:

function check_date( $date, $splitting = '-' ){
    if( trim( $date ) == NULL )
        return 0;
    list( $year, $month, $day ) = explode( $splitting, $date );

    if( intval( $year ) == 0 || intval( $month ) == 0 || intval( $day ) == 0 )
        return 0;
    
    return ( checkdate( $month, $day, $year ) ? 1 : 0 );
}

Password control
int check_password( strin $password_1, string $password_2 [, int $min, int $max ] );

If we have method for string length control done, we can create another method for password control. Passwords are controlled often and everything we need to control is maximal and minimal length of string, which user set.

Method will be very simple. For length control we can use our method for string length control. Here we can control only one set of password, because then we make equal control, and in this case we treat situation, when other password value isn’t in allowed range:

function check_password( $pass1, $pass2, $min = 5, $max = 1000 ){
       if( self::check_length($pass1, $min, $max ) == 0 )
            return 0;

       if( $pass1 != $pass2 )
            return 0;
              
       return 1;
}

IP address control
int check_ip_address( string $address );

Sometimes we will need to control IP address. The address has to be in form: 127.0.0.1 and all different cases will return false value.

Then we will need to have all four number of IP address between 0 - 255 and the last condition will be to have four numbers. At the beginning of the method we will treat also case, when user gave char “.” at the end of IP address:

function check_ip_address( $ip ){
    $ip = trim( $ip);
    if( empty( $ip ) )
        return 0;
    $ip = ( substr( $ip, -1, 1 ) == '.' ? substr( $ip, 0, -1 ) : $ip );
    
    if( count( $ip = explode('.', $ip ) ) != 4 )
        return 0;
    
    foreach( $ip  as $value ){
        if( !is_numeric( $value ) || $value < 0 || $value > 255 )
            return 0;
    }
    return 1;
}

URL address control
int check_url( string $url [, int $check_domain ] );

What we do often is URL address control. By URL address is mostly the most important to control protocol, which has been entered, because users often order to this input absurd chars.

In array we will define, which all protocols will be allowed (in this case only http, https, ftp, ... ). One value of input parameters will be URL address. This method can control if URL address exists too. This example won’t work in the windows system, therefore is this control established as second optional parameter:

function check_url( $url_addres, $check_domain = 0 ){
    if( trim( $url_addres ) == NULL )
        return 0;
    $scheme = array('http', 'https', 'ftp');
    $url = parse_url( trim( $url_addres ) );
    if( in_array( $url['scheme'], $scheme) == 0 )
        return 0;
    if( $url['host'] == NULL )
        return 0;
    
    if( $check_domain == 0 )
        return 1;        
        
    if ( getmxrr ( $url['host'], $MX ) )
		return $MX;
	else 
		return 0;
}

Phone number control
int check_phone( string $pnumber, [, int $length ] );

Phone number control we have to make on the base of some input mask (form, which phone number is entered in). In this case phone number will be requested in form: +xxx xxx xxx xxx. First parameter will be then phone number. We will create also second optional parameter just to be sure, which will define maximal length of phone number:

function check_phone( $pnumber, $length = 12 ){
    //phone number format: +xxx xxx xxx xxx
    $pnumber = trim( $pnumber );
    if( substr( $pnumber, 0, 1 ) != '+') 
        return 0;

    $replace = array( ' ', '+' );
    $replacent = array('', '');
    $pnumber = str_replace( $replace, $replacent, $pnumber);
    
    if( strlen( $pnumber ) != $length ){
        return 0;   
    }
    
    return 1;
}

We can also control extra, if the whole phone number is in numeric format.

Postcode control
int check_zipcode( string $zip_code [, int $max_length ] );

Postcode control may be often useful. Postcode can be in this case only in numeric format with space char extra. Input parameters are value of postcode and optional parameter is postcode length without space chars. Spaces are cut before control:

function check_zipcode( $zip_string, $length = 5 ){
    if( $zip_string == NULL || !is_int( $length ) )
        return 0;
    
    $chars = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    $zip_string = trim( $zip_string );    
    
    for( $i = 0; $i < strlen( $zip_string ); $i++ ){
        if( !in_array( $zip_string[ $i ], $chars ) && ord(" ") != ord( $zip_string[ $i ] ) )
            return 0;
    }

    if( $length == 0 )
        return 1;
    $zip_string = str_replace(' ', '', $zip_string );
    
    return ( strlen( $zip_string ) != $length ? 0 : 1 );
}

Email control
int check_email( string $email [, int $check_domain ] );

Very important method is email control. This method enable, in the same way like method for URL address control, to control domain extra. But this function won’t be function under windows system, and therefore this function is restricted with optional parameter:

function check_email( $var, $check_domain = 0 ){
    if( empty( $var ) )
        return 0;
    $return = ( !eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $var ) ? 0 : 1 );
    
    if( $check_domain == 0 )
        return $return;
        
     list ( $username, $domain ) = split ("@",$var );
		if ( getmxrr ( $domain, $MX ) )
			return $MX;
		else 
			return 0;
}

Personal identification number ( PIN ) control
check_personal_identification_number( string $pin );

The last method for control, which we will create and which can be useful, is PIN control. PIN mask is little complicated than phone mask. We must control all entered numbers, which are different from male and female.

This method has one input parameter, which is just PIN:

function check_personal_idenfication_number( $number ){
    //516111/458
    $len = strlen( strval( intval( str_replace('/', '', $number ) ) ) );
    if( $len < 9 || $len > 10 )
        return 0;
        
    $pin['year'] = substr( $number, 0, 2);
    $pin['month'] = intval( substr( $number, 2, 2 ) );
    $pin['day'] = intval( substr( $number, 4, 2 ) );
    $pin['ending'] = substr( $number, 6, 3);
    $pin['check_number'] = substr($number, 9, 1);
    
    //year
    if( $len == 9 ){
        if( $pin['year'] > 53 )
            return 0;
        else
            $pin['year'] = 19 . $pin['year'];
    }
    else if( $len == 10 ){
        $pin['year'] = ( date('y') >= $pin['year'] ? 20 . $pin['year'] : 19 . $pin['year'] );   
    }
        
    //month
    if( $pin['month'] > 50  && $pin['month'] < 63 )
        $pin['month'] -= 50;
    if( $pin['month'] < 1 || $pin['month'] > 12 )
        return 0;
        
    //check days
    if( $pin['day'] >  cal_days_in_month(CAL_GREGORIAN, $pin['month'], $pin['year'] ) )
        return 0;

    return 1;
}

These are all of simple controls of input values.

Strip slashes

We will create one method extra, which will be cared about magic quotes cut, and that according to set directive Magic_Quotes_GPC in php.ini:

function _stripslashes( & $array ){
    $magic_quotes_gpc = get_magic_quotes_gpc();
    if( is_array( $array ) ){
        while ( list ( $key, $value ) = each ( $array ) ) {
            $array[ $key ] = trim( htmlspecialchars( $magic_quotes_gpc == 1 ? stripslashes( $value ) : $value ) ); 
        }
    }
    else{
        $array = trim( htmlspecialchars( $magic_quotes_gpc == 1 ? stripslashes( $array ) : $array ) );
    }
}

Input value is array transmitted as reference.

Let see, what we have created:

class check_variable{
    function __construct(){}    
    
    function check_phone( $pnumber, $length = 12 ){
        //phone number format: +xxx xxx xxx xxx
        $pnumber = trim( $pnumber );
        if( substr( $pnumber, 0, 1 ) != '+') 
            return 0;
            
        //$replace = array( 0x20, 0x43 );
        $replace = array( ' ', '+' );
        $replacent = array('', '');
        $pnumber = str_replace( $replace, $replacent, $pnumber);
        
        if( strlen( $pnumber ) != $length ){
            return 0;   
        }
        
        return 1;
    }
        
    function _stripslashes( & $array ){
        $magic_quotes_gpc = get_magic_quotes_gpc();
        if( is_array( $array ) ){
            while ( list ( $key, $value ) = each ( $array ) ) {
                $array[ $key ] = trim( htmlspecialchars( $magic_quotes_gpc == 1 ? stripslashes( $value ) : $value ) ); 
            }
        }
        else{
            $array = trim( htmlspecialchars( $magic_quotes_gpc == 1 ? stripslashes( $array ) : $array ) );
        }
    }
    
    function check_email( $var, $check_domain = 0 ){
        if( empty( $var ) )
            return 0;
        $return = ( !eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $var ) ? 0 : 1 );
        
        if( $check_domain == 0 )
            return $return;
            
         list ( $username, $domain ) = split ("@",$var );
		    if ( getmxrr ( $domain, $MX ) )
			    return $MX;
		    else 
			    return 0;
    }
    
    function check_length( $var, $min, $max ){
        if( !is_int( $min ) || !is_int( $max ) )
            return 0;
            
        switch( gettype( $var ) ){
            case 'string' : {
                return ( strlen( trim( $var ) ) < $min || strlen( trim( $var ) ) > $max ? 0 : 1 );
                //break;   
            }
            case 'array' : {
                //recursive count
                $count = count( $var, COUNT_RECURSIVE );
                return ( $count < $min || $count > $max ? 0 : 1 );
                //break;
            }
            default: return 0;   
        }  
    } 
        
    function check_date( $date, $splitting = '-' ){
        if( trim( $date ) == NULL )
            return 0;
        list( $year, $month, $day ) = explode( $splitting, $date );

        if( intval( $year ) == 0 || intval( $month ) == 0 || intval( $day ) == 0 )
            return 0;
        
        return ( checkdate( $month, $day, $year ) ? 1 : 0 );
    }
        
    function check_url( $url_addres, $check_domain = 0 ){
        if( trim( $url_addres ) == NULL )
            return 0;
        $scheme = array('http', 'https', 'ftp');
        $url = parse_url( trim( $url_addres ) );
        if( in_array( $url['scheme'], $scheme) == 0 )
            return 0;
        if( $url['host'] == NULL )
            return 0;
        
        if( $check_domain == 0 )
            return 1;        
            
        if ( getmxrr ( $url['host'], $MX ) )
		    return $MX;
	    else 
		    return 0;
    }
        
    function check_password( $pass1, $pass2, $min = 5, $max = 1000 ){
           if( $pass1 != $pass2 )
                return 0;
           
           if( self::check_length($pass1, $min, $max ) == 0 )
                return 0;
           
           return 1;
    }
        
    function check_personal_idenfication_number( $number ){
        //516111/458
        $len = strlen( strval( intval( str_replace('/', '', $number ) ) ) );
        if( $len < 9 || $len > 10 )
            return 0;
            
        $pin['year'] = substr( $number, 0, 2);
        $pin['month'] = intval( substr( $number, 2, 2 ) );
        $pin['day'] = intval( substr( $number, 4, 2 ) );
        $pin['ending'] = substr( $number, 6, 3);
        $pin['check_number'] = substr($number, 9, 1);
        
        //year
        if( $len == 9 ){
            if( $pin['year'] > 53 )
                return 0;
            else
                $pin['year'] = 19 . $pin['year'];
        }
        else if( $len == 10 ){
            $pin['year'] = ( date('y') >= $pin['year'] ? 20 . $pin['year'] : 19 . $pin['year'] );   
        }
            
        //month
        if( $pin['month'] > 50  && $pin['month'] < 63 )
            $pin['month'] -= 50;
        if( $pin['month'] < 1 || $pin['month'] > 12 )
            return 0;
            
        //check days
        if( $pin['day'] >  cal_days_in_month(CAL_GREGORIAN, $pin['month'], $pin['year'] ) )
            return 0;

        return 1;
    }
        
    function check_ip_address( $ip ){
        $ip = trim( $ip);
        if( empty( $ip ) )
            return 0;
        $ip = ( substr( $ip, -1, 1 ) == '.' ? substr( $ip, 0, -1 ) : $ip );
        
        if( count( $ip = explode('.', $ip ) ) != 4 )
            return 0;
        
        foreach( $ip  as $value ){
            if( !is_numeric( $value ) || $value < 0 || $value > 255 )
                return 0;
        }
        return 1;
    }
        
    function check_zipcode( $zip_string, $length = 0 ){
        if( $zip_string == NULL || !is_int( $length ) )
            return 0;
        
        $chars = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $zip_string = trim( $zip_string );    
        
        for( $i = 0; $i < strlen( $zip_string ); $i++ ){
            if( !in_array( $zip_string[ $i ], $chars ) && ord(" ") != ord( $zip_string[ $i ] ) )
                return 0;
        }

        if( $length == 0 )
            return 1;
        $zip_string = str_replace(' ', '', $zip_string );
        
        return ( strlen( $zip_string ) != $length ? 0 : 1 );
    }
}

 


linkuj topclanky
Coments (4665)

Author: Zaachi
Published: 18.9.2007 12:22:02
TOPLIST.cz

rss coments img img img