12 August 2012

Creating member login/register system using PHP and MySQL

In this tutorial, I am going to teach you how to create a simple login system using PHP and MySQL database.
Before beginning, I am making assuming that you have basic knowledge on PHP coding. However you may understand what I am doing if you have basic programming concepts.

Now let us summarize what we’ll be doing.

First we’ll be creating a database table with username, password and email (optional) columns. After creating the database, we’ll be using two input forms to login in login.php page. And three input forms in register.php. Then we’ll be verifying the entered username and password value with that on in the MySQL database disabling the un-authorized access to the specific part of your page. If your password matches with the record in the database then you’ll be automatically redirected to member.php which is only accessible to members.

For login

For register

So let’s begin.

First create a database:


    <?php

    //connects to the database

    $con= mysql_connect(“localhost”, “username”, “password”);

    // creates command new database named user_logs

    $dbase= “CREATE DATABASE user_logs”;

    //creates new database using mysql_query function.

    mysql_query($dbase, $con);

    //selects recently created user_logs database

    mysql_select_db(“user_logs”, $con);

    //creates new user table with columns in user_logs dtabase.

    $sqls = “CREATE TABLE user

    (

    username VARCHAR(15),

    password VARCHAR(15),

    email VARCHAR(50),

    userID int NOT NULL AUTO_INCREMENT,

    PRIMARY KEY(userID)

    )”;

    // Execute query

    mysql_query($sqls, $con);

    // closes the connection.

    mysql_close($con);

    ?> 




In the above setup, username and password have maximum number of character limited to 15.

You can add other columns to the table.

For example, if you want email address too then refer to the following sample of MySQLcommand.


    CREATE TABLE table_name

    (

    Column1 VARCHAR(15),

    Column2 VARCHAR(15),

    Column3 VARCHAR(50),

    columnID int NOT NULL AUTO_INCREMENT,

    PRIMARY KEY(columnID)

    )”;



Now we are done with the database. Save the above file as “create_db.php”.

Creating register form:


    <form action=”register.php” method=”post”>

    Name: <input />

    password: <input name=”pwd” />

    email: <input name=”mail”/>

    <input/>

    </form>

    Now lets make a backend code using PHP.

    <?php

    //connects to the database.

    $con= mysql_connect(“localhost”, “root”);

    // if everything is empty then returns with message.

    if (empty($_POST["user"]) || empty($_POST["pwd"]) || empty($_POST["mail"]) && isset($_POST["save"]))

    {

    echo “Please enter your username with maximum 15 characters and password with maximum 15 characters properly with valid email ID.”;

    }

    // if values are properly posted, applies md5 hash to the password.

    if (isset($_POST["save"]) && $_POST["user"] && $_POST["pwd"] && $_POST["mail"])

    {

    $user = $_POST["user"];

    $_POST['pwd'] = md5($_POST['pwd']);

    $pwd = $_POST['pwd'];

    $mail = $_POST["mail"];

    }

    // again when the value are properly posted, queries the database if the same username exists. If true then returns with message else writes on the database.

    if (isset($_POST["save"]) && $_POST["user"] && $_POST["pwd"] && $_POST["mail"])

    {

    mysql_select_db(“user_logs”, $con);

    $checkuser = mysql_query(“SELECT username FROM user WHERE username=’$user’”);

    $username_exist = mysql_num_rows($checkuser);

    }

    if($username_exist > 0)

    {

    echo “The username you’ve request has already been taken, please try any other username.”;

    }

    elseif (isset($_POST["save"]) && $_POST["user"] && $_POST["pwd"] && $_POST["mail"]) {

    mysql_select_db(“user_logs”, $con);

    $write = “INSERT INTO user (username, password, email) VALUES (‘$user’, ‘$pwd’, ‘$mail’)”;

    mysql_query($write, $con);

    echo “Congraturlations, you’ve been registered”;

    mysql_close($con);

    }

    ?>

    <br />

    <span style=”text-align:right;”>Already registered? <a href=”login.php”>Click here to Login</a></span>




Save the above PHP script and register form in separate register.php file.

Now we will be creating forms for login and registration.

The form below is for login.php.



    <form action=”login.php” method=”post”>

    Name: <input />

    password: <input name=”pwd” />

    <input />

    </form>


This time we’ll be applying this form inside the PHP backend code instead of applying it separately as we did with register.php.

The above form contains a submit button with username and password input field.

The backend part of login.php is somewhat complex. Before using the code below, let me tell you what it does.

As the page loads, it checks for the existence of cookies in your browser. If you have cookies already been set then it verifies it with the mysql database. If it comes true then it will redirect login.php to member.php(where your member’s page resides).

But if you don’t have cookies set in your browser, then it will load a user login form. When you log in, if the username and password matches with the one in database it will set a cookies for both username and password in your browser. And finally redirect your page to member.php. Else if your login information doesn’t matches, it returns with Try-again message and a login form.



    <?php

    //Checks if the cookie exists, if true then verifies it with the database.

    if (isset($_COOKIE['user']) && isset($_COOKIE['pass']))

    {

    $usar = $_COOKIE['user'];

    $pswd = $_COOKIE['pass'];

    $con = mysql_connect(“localhost”, “root”) or die(“cannot connect”);

    mysql_select_db(“user_logs”, $con) or die(“cannot select DB”);

    $sql=”SELECT * FROM user WHERE username=’$usar’”;

    $result=mysql_query($sql, $con);

    $info=mysql_fetch_array($result);

    //if verified redirects your page to member.php

    if (mysql_num_rows($result)==1 && $pswd!= $info['password'])

    {

    header (“Location: member.php”);

    }

    }

    // other wise if you don’t have cookies set you’ll already be welcomed with the login form which is executed from the bottom of this PHP page. And if you input your username and password it will check and verify with the mysql database.

    if (isset($_POST['save']))

    {

    $con = mysql_connect(“localhost”, “root”) or die(“cannot connect”);

    mysql_select_db(“user_logs”, $con) or die(“cannot select DB”);

    $user = $_POST["user"];

    $pwd = md5($_POST['pwd']);

    $sql=”SELECT * FROM user WHERE username=’$user’”;

    $result=mysql_query($sql, $con);

    $info=mysql_fetch_array($result);

    if (mysql_num_rows($result)==1 && $pwd!= $info['password'])

    {

    $hour = time() + 60;

    setcookie(user, $_POST['user'], $hour);

    setcookie(pass, $_POST['pwd'], $hour);

    header (“Location: member.php”);

    }

    //if false user information then returns with try-again message and a login form.

    else {

    echo “Access denied. Try re-entering your username and password, if you haven’t registered yet, <a href=’register.php’>Click here to register</a>”;

    echo “<title>Login module</title>”;

    echo “<form action=’login.php’ method=’post’>”;

    echo “Name: <input type=’text’ name=’user’ />”;

    echo “password: <input type=’password’ name=’pwd’ />”;

    echo “<input type=’submit’ name=’save’/>”;

    echo “</form>”;

    }

    }

    // if nothing is true or neutral then loads login form only.

    else {

    echo “<title>Login module</title>”;

    echo “<form action=’login.php’ method=’post’>”;

    echo “Name: <input type=’text’ name=’user’ />”;

    echo “password: <input type=’password’ name=’pwd’ />”;

    echo “<input type=’submit’ name=’save’/>”;

    echo “</form>”;

    }

    ?>



You may be wondering why I used cookies. This is because, if you mistakenly or by change went to login.php, you won’t have to re-enter your username and password again and again.

Now we’ll create a secure page where only members can access. If guests or other tries to access to this page it will prompt for the username and password.

Again we’ll be checking if the cookies exists or not, if the cookies value matches with database, it will welcome you to your member’s page. This is then a secured page where only people with proper username and password can access.


    <?php

    if (isset($_COOKIE['user']) && isset($_COOKIE['pass']))

    {

    $user = $_COOKIE['user'];

    $pwd = $_COOKIE['pass'];

    $con = mysql_connect(“localhost”, “root”) or die(“cannot connect”);

    mysql_select_db(“user_logs”, $con) or die(“cannot select DB”);

    $sql=”SELECT * FROM user WHERE username=’$user’”;

    $result=mysql_query($sql, $con);

    $info=mysql_fetch_array($result);

    if (mysql_num_rows($result)==1 && $pwd!= $info['password'])

    {

    echo “Welcome “;

    echo $_COOKIE['user'];

    echo ” to your main page.”;

    }

    else

    {echo “Sorry wrong password”;}

    }

    else {

    include (“login.php”);

    }

    Instead of following block of codes,

    echo “Welcome “;

    echo $_COOKIE['user'];

    echo ” to your main page.”;



you can add other codes here, for example details of user and their inputs with dynamic webpage.

Note: you may also apply addcslashes() function to every inputs from input forms to get rid of MySQL injections. Make sure that your mysql Host, Username and Password is right one.

Hope from this tutorial you got cleared how to create a PHP and MySQL based secure and advanced login system for your browser.

If you have any question please comment

No comments:

Top 9 Simple Things Every Computer User Should Know How to Do

10.     We all know we should back up our computers, but it’s always one of those things that you’ll set up “one day”.  Setting up a ba...