Tuesday, May 29, 2012

Login System php


Login System php

Login system basically consist of Registration Form,Login form and Login out links, By looking at the sites which have logging systems you may view basically above files only.but behind those viewable files there are some files hidden and do very important role in logging systems I have created fallowing files to make this system work properly and keeping security to avoid unauthorized person access.
  1. register.php- contains registration form.
  2. register-check.php- validates the above form and checks with database the user existence  and conveys correctly filed form data into the MySql table.
  3. dbcon.php- Connects with your database "my_database".
  4. registered.php- inform you have registered successfully and link to login form. 
  5. login_form.pp-collect your login details. 
  6. check_login- check login details are correct or not If correct direct to member area and If not direct to login_ fail.php. 
  7. member-area.php- link to profile area and logout.
  8. login_failed-inform you your login details are wrong.
  9. logout.php- you can logout.
  10. authorisation.php- check  member id is present or direct to access-denied.php
  11. access-denied-access is not allowed who are going to type URL of member-area.php.
dbcon.php
    Create following table in your data base called "my_database".

     CREATE TABLE IF NOT EXISTS `members` (
      `member_id` int(11) NOT NULL AUTO_INCREMENT,
      `firstname` varchar(100) NOT NULL,
      `lastname` varchar(100) NOT NULL,
      `login` varchar(100) NOT NULL,
      `passwd` varchar(32) NOT NULL,
      PRIMARY KEY (`member_id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

    register.php

    <?php
        session_start();
    ?>
    <html>
    <head>

    <title>Registration Form</title>

    </head>
    <body>
    <?php
        if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
            echo '<ul class="err">';
            foreach($_SESSION['ERRMSG_ARR'] as $msg) {
                echo '<li>',$msg,'</li>';
            }
            echo '</ul>';
            unset($_SESSION['ERRMSG_ARR']);
        }
    ?>
    <h2><center><font color=#f09718>Registration Form</font></center></h2>
    <form id="loginForm" name="loginForm" method="post" action="register-check.php">
      <table bgcolor=#f09718 align="center">
        <tr  bgcolor=#ffffff>
          <th>First Name </th>
          <td><input name="fname" type="text" class="textfield" id="fname" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <th>Last Name </th>
          <td><input name="lname" type="text" class="textfield" id="lname" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <th width="124">Login</th>
          <td width="168"><input name="login" type="text" class="textfield" id="login" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <th>Password</th>
          <td><input name="password" type="password" class="textfield" id="password" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <th>Confirm Password </th>
          <td><input name="cpassword" type="password" class="textfield" id="cpassword" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <td>&nbsp;</td>
          <td><input type="submit" name="Submit" value="Register" /></td>
        </tr>
      </table>
    </form>
    </body>
    </html>

    register-check.php

    <?php
      
        session_start();
      
      
        require_once('dbcon.php');
      
      
        $errmsg_arr = array();
      

        $errflag = false;
      
     
        $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        if(!$link) {
            die('Failed to connect to server: ' . mysql_error());
        }
      
        //Select database
        $db = mysql_select_db(DB_DATABASE);
        if(!$db) {
            die("Unable to select database");
        }
      
        //Function to sanitize values received from the form. Prevents SQL injection
        function clean($str) {
            $str = @trim($str);
            if(get_magic_quotes_gpc()) {
                $str = stripslashes($str);
            }
            return mysql_real_escape_string($str);
        }
      
        //Sanitize the POST values
        $fname = clean($_POST['fname']);
        $lname = clean($_POST['lname']);
        $login = clean($_POST['login']);
        $password = clean($_POST['password']);
        $cpassword = clean($_POST['cpassword']);
      
        //Input Validations
        if($fname == '') {
            $errmsg_arr[] = 'First name missing';
            $errflag = true;
        }
        if($lname == '') {
            $errmsg_arr[] = 'Last name missing';
            $errflag = true;
        }
        if($login == '') {
            $errmsg_arr[] = 'Login ID missing';
            $errflag = true;
        }
        if($password == '') {
            $errmsg_arr[] = 'Password missing';
            $errflag = true;
        }
        if($cpassword == '') {
            $errmsg_arr[] = 'Confirm password missing';
            $errflag = true;
        }
        if( strcmp($password, $cpassword) != 0 ) {
            $errmsg_arr[] = 'Passwords do not match';
            $errflag = true;
        }
      
        //Check for duplicate login ID
        if($login != '') {
            $qry = "SELECT * FROM members WHERE login='$login'";
            $result = mysql_query($qry);
            if($result) {
                if(mysql_num_rows($result) > 0) {
                    $errmsg_arr[] = 'Login ID already in use';
                    $errflag = true;
                }
                @mysql_free_result($result);
            }
            else {
                die("Query failed");
            }
        }
      
      
        if($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            header("location: register.php");
            exit();
        }


        $qry = "INSERT INTO members(firstname, lastname, login, passwd) VALUES('$fname','$lname','$login','".md5($_POST['password'])."')";
        $result = @mysql_query($qry);
      
        //Check whether the query was successful or not
        if($result) {
            header("location: register-success.php");
            exit();
        }else {
            die("Query failed");
        }
    ?>

    dbcon.php 

    <?php
        define('DB_HOST', 'localhost');
        define('DB_USER', 'root');
        define('DB_PASSWORD', '');
        define('DB_DATABASE', 'my_database');
    ?>


    register-success.php



    <html>
    <head>
    <title>Registration Successful</title>
    </head>
    <body>
    <h1>Registration Successful</h1>
    <p><a href="login_form.php">Click here</a> to login to your account.</p>
    </body>
    </html>


    login_form.php


    <head>
    <title>Login Form</title>
    </head>
    <body>
    <div align="center">
    <table bgcolor=eda528>
    <h3>Login Form</h3>
    <form id="loginForm" name="loginForm" method="post" action="check_login.php">
      <tr bgcolor=#ffffff>
          <td width="112"><b>Login</b></td>
          <td width="188"><input name="login" type="text" class="textfield" id="login" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <td><b>Password</b></td>
          <td><input name="password" type="password" class="textfield" id="password" /></td>
        </tr>
        <tr bgcolor=#ffffff>
          <td>&nbsp;</td>
          <td><input type="submit" name="Submit" value="Login" /></td>
        </tr>
    </table>
    </td></tr>
    </table>
    </div>

    </form>
    </body>
    </html>

    check_login.php


    <?php
       
        session_start();
       
       
        require_once('dbcon.php');
       
       
        $errmsg_arr = array();
       

        $errflag = false;
       
       
        $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        if(!$link) {
            die('Failed to connect to server: ' . mysql_error());
        }
       
        //Select database
        $db = mysql_select_db(DB_DATABASE);
        if(!$db) {
            die("Unable to select database");
        }
       
       
        function clean($str) {
            $str = @trim($str);
            if(get_magic_quotes_gpc()) {
                $str = stripslashes($str);
            }
            return mysql_real_escape_string($str);
        }
       
       
        $login = clean($_POST['login']);
        $password = clean($_POST['password']);
       
        //Input Validations
        if($login == '') {
            $errmsg_arr[] = 'Login ID missing';
            $errflag = true;
        }
        if($password == '') {
            $errmsg_arr[] = 'Password missing';
            $errflag = true;
        }
       
        //If there are input validations, redirect back to the login form
        if($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            header("location: login-form.php");
            exit();
        }
       
       
        $qry="SELECT * FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'";
        $result=mysql_query($qry);
       
        //Check whether the query was successful or not
        if($result) {
            if(mysql_num_rows($result) == 1) {
                //Login Successful
                session_regenerate_id();
                $member = mysql_fetch_assoc($result);
                $_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
                $_SESSION['SESS_FIRST_NAME'] = $member['firstname'];
                $_SESSION['SESS_LAST_NAME'] = $member['lastname'];
                session_write_close();
                header("location: member-area.php");
                exit();
            }else {
                //Login failed
                header("location: login_failed.php");
                exit();
            }
        }else {
            die("Query failed");
        }
    ?>

    member-area.php


    <?php
    require_once('authorisation.php');
    ?>
    <head>
    <title>Member Area</title>
    </head>
    <body>
    <center><h1>Welcome <?php echo $_SESSION['SESS_FIRST_NAME'];?></h1>
    <a href="profile.php"><?php echo $_SESSION['SESS_FIRST_NAME'];?>&nbsp;Enter Your Profile</a> | <a href="logout.php">Logout</a>
    <p>members area. </p></center>
    </body>
    </html>


    login_failed.php


    <head>
    <title>Login Failed</title>
    <body>
    <h1>Login Failed </h1>
    <p align="center">&nbsp;</p>
    <h4 align="center" class="err">Login Failed!<br />
      Please check your username and password</h4>
    </body>
    </html>

    profile.php
    you can create your own file

    logout.php


     <?php
      
        session_start();
      
      
        unset($_SESSION['SESS_MEMBER_ID']);
        unset($_SESSION['SESS_FIRST_NAME']);
        unset($_SESSION['SESS_LAST_NAME']);
    ?>
    <html>
    <head>

    <title>Logged Out</title>

    </head>
    <body>
    <h1>Logout </h1>
    <p align="center">&nbsp;</p>
    <h4 align="center" class="err">You have been logged out.</h4>
    <p align="center">Click here to <a href="login_form.php">Login</a></p>
    </body>
    </html>

    authorisation.php 

    <?php
        //Start session
        session_start();
      
        //Check whether the session variable SESS_MEMBER_ID is present or not
        if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
            header("location: access-denied.php");
            exit();
        }
    ?>

    access-denied.php 


    <html>
    <head>
    <title>Access Denied</title>
    </head>
    <body>
    <h1>Access Denied </h1>
    <p align="center">&nbsp;</p>
    <h4 align="center" class="err">Access Denied!<br />
      You do not have access to this resource.</h4>
    </body>
    </html>



    1 comment:

    1. Instead of rolling your own login system, you should use prepackaged solutions like:

      http://barebonescms.com/documentation/sso/

      That is an enterprise-grade Single Sign-On system.

      ReplyDelete