Building an Login System in PHP

Categories: php

Get SourceWe will see how a simple login system can be build using php. First of all, we must create a database with any random name you like and fire the following SQL query to create a table ‘userpass’ with fields ‘id’,'username’ and ‘password’.

CREATE TABLE IF NOT EXISTS `userpass` (
`id` INT(4) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(65) NOT NULL DEFAULT '',
`password` VARCHAR(65) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

After getting ready with the database, our first step is to create a registration form. Following is the source of register.php. It’s an simple form. I make use of external style-sheets to make it look better, you can download the whole source by clicking on the icon above.

register.php
Registration form

<html>
<head>
    <link rel="stylesheet" href="style.css" type="text/css" charset="utf-8">
    <link rel="stylesheet" href="style2.css" type="text/css" charset="utf-8">
    <title>Register</title>
</head>
<body>
<div id="main">
    <div id="top"></div>
    <div id="middle">
        <h1>Registration Form</h1>
        <?php
        if(isset($_GET['err']))
        {
            if($_GET['err']==1)
                echo '<div class="error">Please enter data in all fields.</div>';
            else if($_GET['err']==2)
                echo '<div class="error">Passwords didn\'t match</div>';
            else if($_GET['err']==3)
                echo '<div class="error">Username already exists, please use another one!</div>';
        }
        ?>
        <form action="register_me.php" method="post">
            <div id="boxtop"></div><div id="boxmid">
                <div class="section">
                    <span>Username:</span>
                    <input type="text" name="username" value="Username" />
                </div> 
                <div class="section">
                    <span>Password:</span>
                    <input type="password" name="password" value="Password" />
                </div>
                <div class="section">
                    <span>Retype Password:</span>
                    <input type="password" name="password2" value="Password" />
                </div>
            </div><div id="boxbot"></div>
            <div class="text" style="float: left;"><p>Already got an account ?</p><p><a href="index.php">Login</a>.</p></div>
            <div class="text" style="float: right;">
            <input type="submit" value="Register" name="register" class="submit" />
        </div>
        <br style="clear:both; height: 0px;" />
    </div>
    <div id="bottom"></div>
</div>
</body>
</html>

register_me.php
At this page, we usually establish connection to the database, select the database and insert the data from registration form to the table. It is inevitable to check various aspects like if the username already exists in the table or not. Please have a look at comments in the code to be more clear about what it does.

<?php
    //Connect and select a datbase
    mysql_connect("localhost", "dbuser" , "dbpass" )or die("cannot connect to database server");
    mysql_select_db("dbname")or die("cannot select the database");
   
    //if form is submitted
    if(isset($_POST['register']))
    {  
        //check if every fields are entered
        if(!$_POST['username'] | !$_POST['password'] | !$_POST['password2'])
        {
            header("location:register.php?err=1");
        }
        //check if password is verified
        else if($_POST['password'] != $_POST['password2'])
        {
            header("location:register.php?err=2");
        }
        else
        {
            $username = $_POST['username'];
            $password = $_POST['password'];
            //query to know whether a username already exists
            $sql = "SELECT username FROM userpass WHERE username='".$username."'";
            $resource = mysql_query($sql) or die("username check error");
            $check = mysql_num_rows($resource);
            if($check == 1)
            {
                header("location:register.php?err=3");
            }
            else
            {
                //enter details to the table
                $username = addslashes($username);
                $password = addslashes($password);
                $query = "INSERT INTO userpass (username, password) VALUES ('".$username."','".$password."')"; 
                $register = mysql_query($query) or die("insertion error");
                header("location:index.php?reg");
            }
        }
    }      
?>

After successful registration, its time to build a login form. Here, we name it as index.php
index.php
login form

<html>
<head>
    <link rel="stylesheet" href="style.css" type="text/css" charset="utf-8">
    <link rel="stylesheet" href="style2.css" type="text/css" charset="utf-8">
    <title>Login</title>
</head>
<body>
<div id="main">
    <div id="top"></div>
    <div id="middle">
       
        <?php
        if(isset($_GET['reg']))
            echo "<h1>Registration succesfull, please login</h1>";
        else if(isset($_GET['logout']))
            echo "<h1>Logged out Succesfully!</h1>";
        else
            echo "<h1>Login System</h1>";
        if(isset($_GET['err']))
        {
            if($_GET['err']==1)
                echo '<div class="error">Pleae enter both username and password</div>';
            if($_GET['err']==2)
                echo '<div class="error">Incorrect username or password</div>';
        }
        ?>
        <form action="checklogin.php" method="post">   
            <div id="boxtop"></div><div id="boxmid">       
                <div class="section">
                    <span>Username:</span>
                    <input type="text" name="username" value="Username" />
                </div>     
                <div class="section">
                    <span>Password:</span>
                    <input type="password" name="password" value="Password" />
                </div>
            </div><div id="boxbot"></div>
            <div class="text" style="float: left;"><p>Haven't got an account? Want one?</p><p><a href="register.php">Register</a>.</p></div>
            <div class="text" style="float: right;">
            <input type="submit" value="Login" name="login" class="submit" />
        </div>
        <br style="clear:both; height: 0px;" />
    </div>
    <div id="bottom"></div>
</div>
</body>
</html>

The form at index.php (login form) POSTs data to checklogin.php. This file checks if the provided login is valid or not.
checklogin.php

<?php
    //connect and select db
    mysql_connect("localhost", "dbuser" , "dbuser" )or die("cannot connect to database server");
    mysql_select_db("dbname")or die("cannot select the database");
    //check if form is submitted
    if(isset($_POST['login']))
    {
        //check if every field is entered
        if(!$_POST['username'] | !$_POST['password'])
        {
            header("location:index.php?err=1");
        }
        else
        {
            //check if username and pass exists in db
            $username = stripslashes($_POST['username']);
            $password = stripslashes($_POST['password']);
            $query = "SELECT * FROM userpass WHERE username='".$username."' and password='".$password."'";
            $resource = mysql_query($query);
            $count=mysql_num_rows($resource);
            if($count == 1)
            {  
                //if yes, start session and set a variable
                session_start();
                $_SESSION['logged_in'] = 1;
                header("location:loggedin.php");
            }
            else
            {
                //if not, redirect back to login page showing an error
                header("location:index.php?err=2");
            }
        }
    }

?>

If login is successful, loggedin.php is loaded. If checks for the session variable, whether it’s set or not. If it’s set. it means the user is logged in and shows an logout button which would unset the session variable.
loggedin.php
logged in

<?php
    //start session and check if session variable is set
    session_start();
    if(!isset($_SESSION['logged_in']))
    {
        header("location:index.php");
    }
    // if yes, show status and an logout button
    else
    {
        echo "logged in";
        //if logout button is clicked, unset the session variable and redirect to index.php?logout
        if(isset($_GET['logout']))
        {
            unset($_SESSION['logged_in']);
            header("location:index.php?logout");
        }
        echo "<br /><a href=\"loggedin.php?logout\">Logout</a>";
    }
?>

You can then click the logout button and it will unset the session variable and redirect to index.php?logout, which looks something like
logged out

Share on  Twitter  Facebook  Google Reader  Orkut Tags: login, php, POST, session, session_start, sql
5 Comments

Related Posts

  • Ways to download a file using PHP

5 Comments

  • tanim says:
    May 25, 2010 at 12:09 pm

    awsome, i find da addrs in facebuk, u gave it someone. ur post is more easi i ever seen.

  • Anil Dewani says:
    May 27, 2010 at 6:28 am

    Thanks tanim, keep visiting. :)

  • Dinesh says:
    August 3, 2010 at 5:41 am

    hi anil
    I like ur website

    I just want to know that frm where u got this inspiration to make a website

    In ur website especially i like the codings of
    PHP login

    keep progressing

  • Anil Dewani says:
    August 9, 2010 at 6:27 pm

    Hi Dinesh, thanks for your compliments :)

  • andy says:
    August 12, 2010 at 6:30 am

    Hi, Nice script and its working verywell, I got what I wanted for my website!

    Thanks :D :P

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

« Rapidshare Download Manager Script in Bash — Creating a Counter Strike 1.6 No-Steam Linux Server »

Programming Blog

Hey everyone.
My name is Anil Dewani
and this is my programming blog.
I mostly code in php and bash.
Click here to know more about me.
RSS | Atom
    • About Me
    • Contact Me
  • Find it!

  • Subscribe

    Enter your email address:

  • Categories

    • bash
    • Internet Marketing
    • Linux
    • php
    • Windows Server
  • Tags

    > awk backup script bash benchmarking brute force counter strike cron cs 1.6 cs 1.6 server curl cut dev dialog domain file_get_contents fsockopen gaming getopts hash hlds login md5 null pastebin php POST rapidshare rm server session session_start sha1 sql STDERR STDIN STDOUT twitter unix wget whois youtube
  • > awk backup script bash benchmarking brute force counter strike cron cs 1.6 cs 1.6 server curl cut dev dialog domain file_get_contents fsockopen gaming getopts hash hlds login md5 null pastebin php POST rapidshare rm server session session_start sha1 sql STDERR STDIN STDOUT twitter unix wget whois youtube
    Monospace WordPress Theme by Vinicius Massuchetto