Username & Password Validation

Results 1 to 4 of 4
  1. #1
    hi academic is offline
    MemberRank
    Jun 2010 Join Date
    AustraliaLocation
    484Posts

    thumbs up Username & Password Validation

    Hello Programmers!

    Just recently the other day I was thinking about how I acquired the PHP language and because majority of my knowledge was acquired through forums like this community and many others for that fact, I thought I might share a bit of what I know from what I've learned in the last 12 months or so.

    This may come in handy for any new beginners to PHP. I will be releasing snippets of code that may come in handy, so if you have any requests be sure to message me or just leave a post and I will try my best to get around to doing it! I am doing this because I am much better at back end development rather than front end (I suck at designing!).

    However, this is a short sample of a username and password validation using arrays to catch errors. It's probably been done, but the purpose of this post to inform new beginners and showing other ways of implementing and using alternative methods.

    Annnnyhow! Enough talk, here it is.

    View on PasteBin
    Download from PasteBin


  2. #2
    Digital Horizon KristiansJ is offline
    MemberRank
    Jul 2012 Join Date
    203Posts

    Re: Username & Password Validation

    You are confusing newbies with this, when i read the title, i thought it would include some custom database injection prevention script, but its just validating string length, etc.. noobs may thing that this can protect from database related injection too...

    anyway here is mine contribution on this matter :D

    PHP Code:
    <?php
    // if(!defined(__SYSTEM__)){die();}

    class DataType
    {
        const 
    STRING   0;
        const 
    NUMERIC  1;
        const 
    ALPHANUM 2;
        const 
    HTML     3;
        const 
    RAW      4;
        const 
    EMAIL    5;
        const 
    COMMENTS 6;
        const 
    ADMIN    7;
    }

    class 
    mssql
    {
        private 
    $database;
        private 
    $validation NULL;
        private 
    $error NULL;
        public 
    $execute true;
        private 
    $query_;
        function 
    __construct($server,$database,$login,$password)
        {
            try
            {
                
    $this->database = new PDO('sqlsrv:server='.$server.';Database ='.$database$login$password);

            }
            catch (
    PDOException $e)
            {
               
    //echo $e;
                
    $_SESSION['databaseOnline'] = 'false';
            }

        }

        function 
    setValidation($minLen false,$maxLen false,$required true)
        {
            
    $this->validation['minLen']   = $minLen;
            
    $this->validation['maxLen']   = $maxLen;
            
    $this->validation['required'] = $required;

            return 
    $this;
        }

        function 
    setValidationEx($keywordCheck true,$replaceQuerySpcChr true)
        {
            
    $this->validation['keywordCheck'] = $keywordCheck;
            
    $this->validation['replaceQuerySpcChr'] = $replaceQuerySpcChr;
            return 
    $this;
        }

        function 
    set($field,$key,$value,$type NULL,$pdoType PDO::PARAM_STR,$encrypt false)
        {
            switch(
    $type)
            {
                case 
    DataType::ALPHANUM:
                    if(!
    ctype_alnum($value))
                    {
                        
    $this->error[] = 'Error: '.$field.' is not valid, this field must contain only alphanumeric characters (AZaz0-9)';
                        
    $this->execute false;
                    }
                    break;
                case 
    DataType::HTML:

                    break;
                case 
    DataType::NUMERIC:
                    if(!
    is_numeric($value))
                    {
                        
    $this->error[] = 'Error: '.$field.' is not valid, this field must contain only digits (0-9)';
                        
    $this->execute false;
                    }
                    break;
                case 
    DataType::STRING:
                    if(!
    ctype_alpha($value))
                    {
                        
    $this->error[] = 'Error: '.$field.' is not valid, this field must contain only alphanumeric characters (AZaz0-9)';
                        
    $this->execute false;
                    }
                    break;
                case 
    DataType::EMAIL:
                    if (!
    filter_var($valueFILTER_VALIDATE_EMAIL)) {
                        
    $this->error[] = 'Error: '.$field.' is not valid email address, please recheck and try again';
                        
    $this->execute false;
                    }
                    break;
            }

            if(
    is_array($this->validation))
            {
                if(
    $this->validation['required'] == true AND !isset($value)){
                    
    $this->error[] = 'Error: '.$field.' is not set, please set this field and try again!';
                    
    $this->execute false;
                }

                if(
    is_integer($this->validation['minLen']) || is_integer($this->validation['maxLen'])  AND $type != DataType::NUMERIC)
                {
                    if(
    strlen($value) < $this->validation['minLen'] OR strlen($value) > $this->validation['maxLen'])
                    {
                        
    $this->error[] = 'Error: '.$field.' minimal length is '.$this->validation['minLen'].' and maximal length is '.$this->validation['maxLen'].' characters, Your length:'.strlen($value).'!';
                        
    $this->execute false;
                    }
                }

                if(
    $this->validation['keywordCheck'] == true)
                {
                    
    $badWords = array
                    (
                        
    'drop','update','select','insert',
                        
    'where','replace','order by','group by',
                        
    'truncate','exec'
                    
    );

                    foreach(
    $badWords as $word)
                    {
                        if (
    stripos($value,$word) !== false) {
                            
    $this->error[] = 'Error: '.$field.' contain forbidden word:'.$word.', please remove and try again';
                            
    $this->execute false;
                        }
                    }
                }

                if(
    $this->validation['replaceQuerySpcChr'] == true)
                {
                    
    $value str_replace("'","",$value);
                    
    $value str_replace('"',"",$value);
                }
            }

            if(
    $encrypt == true)
            {

            }

            
    $this->validation NULL;

            if(
    $this->execute == true)
                
    $this->query_->bindParam($key$value$pdoType);
        }

        function 
    addParam($key,$value,$pdoType)
        {
            if(
    $this->execute == true)
                
    $this->query_->bindParam($key$value$pdoType);
        }

        function 
    query($query)
        {
            
    $this->database->setAttributePDO::ATTR_ERRMODEPDO::ERRMODE_WARNING );
            
    $this->query_ $this->database->prepare($query);
        }

        function 
    run()
        {
           if(
    $this->execute == true)
            {
                 return 
    $this->query_->execute();
            }
            return 
    FALSE;
        }

        function 
    resultCount()
        {
            return 
    $this->query_->rowCount();
        }

        function 
    resultArray()
        {
            return 
    $this->query_->fetchAll(PDO::FETCH_ASSOC);
        }

        function 
    GetError()
        {
            return 
    $this->error;
        }

        function 
    GetErrorPDO()
        {
            return 
    $this->database->errorInfo();
        }

        function 
    Clear()
        {
            
    $this->query_ NULL;
            
    $this->validation NULL;
            
    $this->error NULL;
            
    $this->execute NULL;
        }
        function 
    Close()
        {
            
    $this->database NULL;
        }
    }
    Example
    PHP Code:
                $error '';

                if(isset(
    $_POST['register']))
                {
                    
    //
                    // Prepare the query we are working with.
                    //
                    
    $this->getSqlDB->query("SELECT memb___id FROM MEMB_INFO WHERE memb___id=:username OR mail_addr=:email");
                    
    //
                    // Validate and Sanitize query parameters, prepare managed error messages
                    //
                    
    $this->getSqlDB->setValidation(4,12,true)->setValidationEx(true,true)->set('Username','username',$_POST['user_nick'],DataType::ALPHANUM,PDO::PARAM_STR,false);
                    
    $this->getSqlDB->setValidation(4,30,true)->setValidationEx(true,true)->set('Email','email',$_POST['user_email'],DataType::EMAIL,PDO::PARAM_STR,false);

                    
    //
                    // If validation passed then execute queries, else do nothing
                    // If query is valid and it can be executed it will return TRUE on success and FALSE on failure
                    // We will use this variable to determinate if the secound part of this script can be executed
                    //
                    
    $canRegister $this->getSqlDB->run();
                    
    //
                    // Retrieve user information from database
                    //
                    
    $account = &$this->getSqlDB->resultArray();
                    
    // Catch occurred errors within variable validation if any...
                    // We run can run query after we check for errors, if query has errors,
                    // it won't be executed anyway, so the order do not matter
                    //
                    // GetError() function manages all required errors like min and max size, is numeric and other
                    // so manual variable validation is not required
                    //
                    
    if($this->getSqlDB->GetError() != NULL)
                    {
                        foreach(
    $this->getSqlDB->GetError() as $error)
                        {
                            
    $error .= TWE_Template::showAlertError($error);
                        }
                    }
                    
    //
                    // Check if submitted account exists
                    //
                    //
                    
    if(count($account) > 0)
                    {
                        
    $error .= TWE_Template::showAlertError('Selected account or email is in use!');
                        
    // In this case we need to set canRegister manually since the account check query is valid
                        // and can be executed, but if query is returned rows that means that account or email is in use
                        // so user cant register with his selected account or email!
                        
    $canRegister FALSE;
                    }
                    
    //
                    // Clear previous query data.
                    // Note by cleaning data you do not close previous connection, connection to sql is still open
                    //
                    
    $this->getSqlDB->Clear();

                    if(
    $canRegister == TRUE)
                    {
                        
    //
                        // Prepare the query we are working with.
                        //
                        // Since we validated User Account and Email in first part we do not need to validate them now
                        // We need validate only password.
                        //
                        
    $this->getSqlDB->query("INSERT INTO MEMB_INFO (memb___id,memb__pwd,memb_name,sno__numb,mail_addr,mail_chek,bloc_code,ctl1_code,accessLevel)
                        VALUES ('fdfsdf','gfdgfd','fdsfds','gfdgdfg','gfdgdfg','gvdfgdfg',1,1,1)"
    );
                        
    //
                        // Validate and Sanitize query parameters, prepare managed error messages
                        //

                        //
                        // If validation passed then execute queries, else do nothing
                        // If query is valid and it can be executed it will return TRUE on success and FALSE on failure
                        //
                        
    if($this->getSqlDB->run() == FALSE)
                        {
                            
    // Catch occurred errors within variable validation if any...
                            // We run can run query after we check for errors, if query has errors,
                            // it won't be executed anyway, so the order do not matter
                            //
                            // GetError() function manages all required errors like min and max size, is numeric and other
                            // so manual variable validation is not required
                            //
                            
    if($this->getSqlDB->GetError() != NULL)
                            {
                                foreach(
    $this->getSqlDB->GetError() as $error)
                                {
                                    
    $error .= TWE_Template::showAlertError($error);
                                }
                            }
                            
    $error .= TWE_Template::showAlertError('Account creation has been failed!');
                        }
                    }
                    
    $this->getSqlDB->Clear(); // Clear all used data by database class
                    
    $this->getSqlDB->Close(); // Close all connections to database server
                
    }
            }
        } 
    Last edited by KristiansJ; 27-06-13 at 04:31 PM.

  3. #3
    hi academic is offline
    MemberRank
    Jun 2010 Join Date
    AustraliaLocation
    484Posts

    Username & Password Validation

    Ahh. My apologies.

  4. #4
    <?="Hello World.";?> wutyes is offline
    MemberRank
    Feb 2008 Join Date
    251Posts

    Re: Username & Password Validation

    That enterprise coding... KristiansJ, you have more comments than actual code.



Advertisement