Super Registration via PHP CLASS

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Super Registration via PHP CLASS

    <!-- THIS POST IS NOT FOR NEW PEOPLES WHO JUST START CODING.. TRY TO LEARN THE BASICs First -->

    This class can be used to create records of registered users in MySQL.

    It can take the user name, password, e-mail address from form values submitted via POST method and validates those values.

    The class creates a record in a MySQL table with the new user submitted values.

    WITH THE PROTECTION OF SQLi

    class_registration.php
    PHP Code:

    <?php

    /*

    YUSHA YBN YAKUB

    www.YUSHA.tk

    yusha.tk@GMAIL.COM

    */

    class Registration
    {
        private 
    $registrationDatabaseUserTable;
        private 
    $registrationShowMessage;
        private 
    $registrationPasswordCryptMethod;

        
    /**
         * Sets the database users table
         *
         * @param string $database_user_table
         */
        
    public function setDatabaseUserTable($database_user_table)
        {
            
    $this->registrationDatabaseUserTable=$database_user_table;
        }
        
        
    /**
         * Sets the crypting method
         *
         * @param string $crypt_method - You can set it as 'md5' or 'sha1' to choose the crypting method for the user password.
         */
        
    public function setCryptMethod($crypt_method)
        {
            
    $this->registrationPasswordCryptMethod=$crypt_method;
        }

        
    /**
         * Crypts a string
         *
         * @param string $text_to_crypt -  crypt a string if $this->registrationPasswordCryptMethod was defined.
         * If not, the string will be returned uncrypted.
         */
        
    public function setCrypt($text_to_crypt)
        {
            switch(
    $this->registrationPasswordCryptMethod)
            {
                case 
    'md5'$text_to_crypt=trim(md5($text_to_crypt)); break;
                case 
    'sha1'$text_to_crypt=trim(sha1($text_to_crypt)); break;
            }
           return 
    $text_to_crypt;
        }
        
        
    /**
         * Anti-Mysql-Injection method, escapes a string.
         *
         * @param string $text_to_escape
         */
        
    static public function setEscape($text_to_escape)
        {
            if(!
    get_magic_quotes_gpc()) $text_to_escape=mysql_real_escape_string($text_to_escape);
            return 
    $text_to_escape;
        }
        
        
    /**
         * If on true, displays class messages
         *
         * @param boolean $database_user_table
         */
        
    public function setShowMessage($registration_show_message)
        {
            if(
    is_bool($registration_show_message)) $this->registrationShowMessage=$registration_show_message;
        }
        
        
    /**
         * Prints the class messages with a customized style if html tags are defined
         *
         * @param string $message_text - the message text
         * @param string $message_html_tag_open - the html tag placed before the text
         * @param string $message_html_tag_close - the html tag placed after the text
         * @param boolean $message_die - if on true die($message_text);
         */
        
    public function getMessage($message_text$message_html_tag_open=null$message_html_tag_close=null$message_die=false)
        {
            if(
    $this->registrationShowMessage)
            {
                if(
    $message_die) die($message_text);
                else echo 
    $message_html_tag_open $message_text $message_html_tag_close;
            }
        }
        
        
    /**
         * Register user in the database
         *
         * The user form data needed is: user_name, user_pass, user_confirm_pass, user_mail, user_confirm_mail
         */
        
    public function setUserRegistration()
        {
            if(!
    $this->registrationDatabaseUserTable$this->getMessage('Users table in the database is not specified. Please specify it before any other operation using the method setDatabaseUserTable();','','','true');
            
    $user_name=$this->setEscape($_POST['user_name']);
            
    $user_pass=$_POST['user_pass'];
            
    $user_confirm_pass=$_POST['user_confirm_pass'];
            
    $user_mail=$_POST['user_mail'];
            
    $user_confirm_mail=$_POST['user_confirm_mail'];
            
    $user_crypted_pass=$this->setCrypt($user_pass);
            
    $result_user_name=mysql_query("SELECT * FROM"." ".$this->registrationDatabaseUserTable." "."WHERE user_name='$user_name'");
            
    $result_user_mail=mysql_query("SELECT * FROM"." ".$this->registrationDatabaseUserTable." "."WHERE user_mail='$user_mail'");
            if((
    strlen($user_name)<6) or (strlen($user_name)>16)) $this->getMessage('Entered username length must be of 6 to 16 characters.');
            elseif(
    mysql_num_rows($result_user_name)) $this->getMessage('Entered username already exists in the database.');
            elseif((
    strlen($user_pass)<8) or (strlen($user_pass)>16)) $this->getMessage('Entered password length must be of 8 to 16 characters.');
            elseif(
    $user_pass!=$user_confirm_pass$this->getMessage('Passwords entered do not match.');
            elseif(
    mysql_num_rows($result_user_mail)) $this->getMessage('Entered email already exists in the database.');
            elseif(
    $user_mail!=$user_confirm_mail$this->getMessage('Email addresses entered do not match.');
            elseif(!
    preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{4,})+\.)+([a-zA-Z0-9]{2,})+$/"$user_mail)) $this->getMessage('Email address entered is not valid.');
            else
            {
                if(
    mysql_query("INSERT INTO"." ".$this->registrationDatabaseUserTable." "."(user_name, user_pass, user_mail) VALUES ('$user_name', '$user_crypted_pass', '$user_mail')")) $this->getMessage('Registration was successful.');
            }
        }
    }

    ?>
    registration_example.php

    PHP Code:

    <?php
    // Including the class
    require_once("class_registration.php");

    /// You must establish a connection to the mysql database before using this class
    $database_connection=mysql_connect("localhost""root""password");
    $database_selection=mysql_select_db("users"$database_connection);

    //////////////////////////////

    if(isset($_GET['module']) && ($_GET['module']=="registration"))
    {
        
        
    // Instantiating the class object
        
        
    $registration = new Registration();
        
        
    # Class configuration methods:
        
        // Setting the user table of mysql database
        
    $registration->setDatabaseUserTable('users');
        
        
    // Setting the crypting method for passwords, can be set as 'sha1' or 'md5'
        
    $registration->setCryptMethod('sha1');
        
        
    // Setting if class messages will be shown
        
    $registration->setShowMessage(true);
        
        
    # Creating user account:

        
    $registration->setUserRegistration();
    }
    ?>

    <head>
        <style>
            h1 {
                color: #555;
                font-size: 16px;
                text-decoration: underline;
            }
            form#registration_form {
                background: #FFFFCC;
                border: 1px solid #555;
                color: #555;
                width: 500px;
            }
            label.registration_label {
                float: left;
                margin-left: 50px;
                margin-bottom: 10px;
                width: 200px;
                text-align: left;
            }
            
            label.registration_label:hover {
                background: #FFFFCC;
            }
            
            input.registration_input {
                color: #777;
                font-size: 11px;
                margin-bottom: 10px;
                width: 200px;
            }
            input.registration_submit {
                width: 200px;
                margin-left: 150px;
            }
            hr.registration_hr {
                color: #555;
                clear: both;
                height: 0px;
                margin-bottom: 10px;
                width: 450px;
            }
        </style>
    </head>
    <body>
    <title>BioBeo.com</title>
        <h1>Registration Module:</h1>
        <p><small>Look the source of this file to view the html code used in the form shown below:</small></p>
        <form action="?module=registration" id="registration_form" method="post">
            <p>
                <label class="registration_label">Username: <br/><input name="user_name" class="registration_input"></label>
                <label class="registration_label">Password: <br/><input name="user_pass" type="password" class="registration_input"></label>
                <label class="registration_label">Re-enter Password: <br/><input name="user_confirm_pass" type="password" class="registration_input"></label>
                <label class="registration_label">E-mail: <input name="user_mail" class="registration_input"></label>
                <label class="registration_label">Re-enter E-mail: <input name="user_confirm_mail" class="registration_input""></label>
                <hr class="registration_hr" />
                <input type="submit" class="registration_submit">
            </p>
        </form>
    </body>

    ENJOY... USE THE THANKS BUTTON IF YOU LIKE IT...


    NOTE: I have fully customized this function which integrated to YAML coz I have the support of that language in my server.... so didn't make the SQL for this version..


    Oh and yes.. Please share the sql if you get in work with it...
    Yusha.
    Last edited by BioBeo; 08.11.10, 19:57.

    #2
    SQL created and shared by the request

    SQL:

    Code:
    CREATE TABLE IF NOT EXISTS `users` (
      `user_id` int(11) NOT NULL AUTO_INCREMENT,
      `user_name` varchar(16) NOT NULL,
      `user_pass` varchar(50) NOT NULL,
      `user_mail` varchar(50) NOT NULL,
      `user_active` tinyint(1) NOT NULL,
      PRIMARY KEY (`user_id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
    Enjoy !

    Comment


      #3
      Just so u know, when u set a class method as static, u should access it as class::method else there'll be a E_STRICT notice. So accessing ur setEscape method should not be by $this->setEscape but by self::setEscape. And oh ur class luks messy.

      Added after 21 minutes:

      PHP Code:
      <?php
      /**
       * Simple PHP5 registration class
       */
      class Register {

      /**
       * @var  object Class instance
       * @var  array Class configuration
       */
      public static
      $instance null,
      $config = array
      (
       
      'escape' => TRUE,
       
      'encrypt_method' => 'md5',
       
      'reg_table' => 'ibwf_users',
       
      'show_errors' => TRUE
      );

      /**
       * Get new class instance.
       *
       * @param  array registration config
       * @return  object class instance
       */
      public static function instance(array $config = array())
      {
       if(
      Register::$instance !== NULL)
        return 
      Register::$instance;

       return 
      Register::$instance = new Register($config);
      }

      /**
       * Class constructor.
       */
      protected function __construct(array $config = array())
      {
      // Set configuration individually so we dnt override default config
      // if its not set manually
      if(isset($config['escape']))Register::$config['escape'] = (bool) $config['escape'];
      if(isset(
      $config['encrypt_method']))Register::$config['encrypt_method'] = (string) $config['encrypt_method'];
      if(isset(
      $config['reg_table']))Register::$config['reg_table'] = (string) $config['reg_table'];
      if(isset(
      $config['show_errors']))Register::$config['show_errors'] = (bool) $config['show_errors'];
      }

      public function 
      escape($str)
      {
      if(
      is_array($str))
      {
       foreach(
      $str as $key => $val)
       {
        
      // RECURSSION!
        
      $ret[$key] = $this->escape($val);
       }

       return 
      $ret;
      }
      else
      {
      if(
      get_magic_quotes_gpc())
      {
       
      $str stripslashes($str);
      }
       return 
      mysql_real_escape_string($str);
      }
      }


      public function 
      encrypt($str)
      {
      if(
      is_array($str))
      {
       foreach(
      $str as $key => $val)
       {
        
      // RECURSSION!
        
      $ret[$key] = $this->encrypt($val);
       }

       return 
      $ret;
      }
      else
      {

       
      $encrypt Register::$config['encrypt_method'];
       return 
      $encrypt($str);
      }
      }

      }
      Added after 7 minutes:

      Work with that, add ur other methods. With my class, u can do...
      PHP Code:
      $config = array
      (
       
      'encrypt_method' => 'sha1',
       
      'reg_table' => 'ibwf_users_table'
      );
      $register Register::instance($config);
      // Escape ALL submitted values on the fly
      $_POST $register->escape($_POST);
      $_POST['password'] = $register->encrypt($_POST['password']); 
      Last edited by CreativityKills; 09.11.10, 07:26.

      Comment


        #4
        Thanks for mod... It was over a year ago may be I code on... so I just took that from my archive..............

        Comment

        Working...
        X