Tuesday, August 7, 2012

PHP and MySQL Login System

We are going to create a simple login system written in PHP and using MySQL for the database backend.

I hope that this simple tutorial could help a lot especially to beginners in PHP Web development.


In this tutorial, we will create at least six (6) files:

index.php – default page (as most probably set in Web server configuration)
login.php – when no user is logged, user will be redirected to this page
logout – processes to destroy session and redirects user to login page
auth.inc.php – PHP code that will check if a user is logged or not; if not, it redirects user to login page
dbConfig.inc.php – database configuration
style.css – stylesheet

Files auth.inc.php and dbConfig.inc.php should be placed under folder/directory 'includes', style.css under 'css' while the rest under the document root of your application:

index.php
login.php
logout.php
css/style.css
includes/auth.inc.php
includes/dbConfig.inc.php

There is no registration feature on this login system; I'll add up the next time I would create an advanced version of this application. Data (id, username, password) will be created directly through INSERT SQL command for the purpose of this tutorial.

First, we need to create database `mydb` and create table `member`. For our table `member`, we will only include four (4) fields; you can add more depending on your preference.

CREATE TABLE `member` (
   `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
   `username` VARCHAR(25) NOT NULL,
   `password` VARCHAR(41) NOT NULL,
   PRIMARY KEY(`id`, `username`)
);

We will then create initial data which we are going to use to login:

INSERT INTO `member` (`id`, `username`, `password`)
VALUES(1, 'julez', PASSWORD('secret'));

The Codes

index.php

<?php include './includes/auth.inc.php';?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Home - PHP & MySQL Login System</title>
        <link rel="stylesheet" href="./css/style.css" />
    </head>
    <body>
        <div id="wrapper">
            <div>
                <h5>Login - PHP & MySQL Login System</h5>
            </div>
            <div>
                <?php
                echo "<h2>Welcome ".$_SESSION['username'].'!</h2> ';
                echo '<h4><a href="logout.php?user='.$_SESSION['username'].'">Logout</a></h4>';
                ?>
            </div>
        </div>
    </body>
</html>

login.php

<?php
/*
 * Author:      Julian V. Jupiter
 * Facebook:    facebook.com/julianjupiter
 * Twitter:     twitter.com/dealwithjulez
 * Website:     http://www.jupitersnotebook.co.cc
 */
?>
<?php
include './includes/dbConfig.inc.php';

session_start();
if(isset($_SESSION['isLogged']) && $_SESSION['isLogged'] == 1) {
    header('Refresh: 5; URL = index.php');
    echo '<p>You will be directed to homepagepage in 5 seconds.</p>';
    echo '<p>If your browser doesn\'t redirect automatically, <a href="index.php">click here!</a></p>';
    die();
}

$username = (isset($_POST['username'])) ? trim($_POST['username']) : '';
$password = (isset($_POST['password'])) ? $_POST['password'] : '';
$errors = array();

if(isset($_POST['submit']) && $_POST['submit'] == 'Login') {
    //$errors = array();
    if($username == '') $errors[] = 'Username is required.<br />';
    if($password == '') $errors[] = 'Password is required.<br />';
    if($username != '' && $password) {
        $connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        if(!$connection) echo 'Unable to connect to database server. '.mysql_error();
        $database = mysql_select_db(DB_SCHEMA);
        if(!$database) echo 'Unable to select database. '.mysql_error();
        
        $query = sprintf("SELECT username FROM member WHERE username = '%s' AND password = PASSWORD('%s')",
                mysql_real_escape_string($username), mysql_real_escape_string($password));
        $result = mysql_query($query);
        if(!$result) echo 'Unable to fetch data. '.mysql_error ();
        else {
            if(mysql_num_rows($result) > 0){
                $_SESSION['username'] = $username;
                $_SESSION['isLogged'] = 1;
                header('Refresh: 5; URL = index.php');
                echo '<p>You will be directed to homepage in 5 seconds.</p>';
                echo '<p>If your browser doesn\'t redirect automatically, <a href="index.php">click here!</a></p>';
                die();
            } else {
                $errors[] = "<p>Invalid username/password! Please try again!<br />Please register if you have not done so already.</p>";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">        
        <title>Login - PHP & MySQL Login System</title>
        <link rel="stylesheet" href="./css/style.css" />
    </head>
    <body>
        <div id="wrapper">
            <div>
                <h5>Login - PHP & MySQL Login System</h5>
            </div>
            <?php
            if(count($errors) > 0) {
                echo '<div class="message">';
                foreach ($errors as $error) {
                    echo $error;
                }
                echo '</div>';
            }
            if(isset($_GET['isLoggedOut']) && $_GET['isLoggedOut'] = 'true') {
                echo '<div class="message">';
                    echo "You are now logged out!";
                echo '</div>';
            }
            ?>            
            <div>
                <form name="loginForm" action="<?php echo$_SERVER['PHP_SELF']; ?>" method="POST">
                    <ul>
                        <li>
                            <label for="username">Username:</label>
                            <input type="text" name="username" value="<?php echo $username; ?>" size="20" />
                        </li>
                        <li>
                            <label for="username">Password:</label>
                            <input type="password" name="password" value="<?php echo $password; ?>" size="20" />
                        </li>
                        <br />
                        <li>
                            <input type="submit" value="Login" name="submit" id="button" />
                            <input type="reset" value="Reset" name="reset" id="button" />
                        </li>
                    </ul>
                </form>
            </div>            
        </div>
    </body>
</html>

logout.php

<?php
    session_start();
    session_unset();
    session_destroy();    
    $username = $_GET['user'];
    header('Refresh: 5; URL=login.php?isLoggedOut=true&user='.$username);
    echo '<p>You will be directed to login page in 5 seconds.</p>';
    echo '<p>If your browser doesn\'t redirect automatically, <a href="login.php">click here!</a></p>';          
?>

auth.inc.php

<?php
session_start();
if(!isset($_SESSION['isLogged']) || $_SESSION['isLogged'] != 1) {
    header('Refresh: 5; URL = login.php');
    echo '<p>You will be directed to login page in 5 seconds.</p>';
    echo '<p>If your browser doesn\'t redirect automatically, <a href="login.php">click here!</a></p>';
    die();
}
?>

dbConfig.inc.php

<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', 'admin@12345');
define('DB_SCHEMA', 'mydb');
?>

style.css

body {
    background: #ccccff;
    color: #0000ff;
    font-family: Calibri, Tahoma, Verdana, sans-serif;
}

#wrapper {
    margin: 0;
    padding: 3px;
    border: 1px #0000ff solid;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    width: 600px;
}

a {
    color: #0000ff;
    text-decoration: none;
}

ul {
    list-style: none
}

label {
    display: block;
    list-style-type: none;
}

.message {
    color: #ff0000;
    margin: 0;
    padding: 3px;
    border: 1px #ff0000 solid;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    width: 500px;
}

#button {
    background-color: #0080c0;
    border-color: #2528ad;
    border-style: solid;
    color: #ffffff;
    cursor: pointer;
    padding: 5px;
    border-width: 1px;
    font-size: 15px;
    padding: 3px;
    text-align: center;
    text-decoration: none;
    -webkit-border-radius:5px;
    border-radius:5px;
}

Screenshots

The Login Page

User clicks Login button without entering username and password


User entered only username


User entered only password


User entered wrong username/password or if account does not exist


User entered username and password correctly


The homepage

 
User clicked logout link

User successfully logged out
 


Conclusion

I've tested the codes against PHP Version 5.4.0, MySQL Community Server  Version 5.5.25 and Apache HTTP Server Version 2.2.22; application works fine and I hope this will also work in your PHP programming. Thanks.

Download PDF file.

2 comments:

  1. nice starter blog! ganto rin pag code ko nang login screen ko dati..

    ReplyDelete
  2. Sir pano po pag ang log-in process ay admin at client... yung tipong iba po sa admin at iba rin po sa client? salamat po in advance sir...

    ReplyDelete