Code2Design.com

User login

The Layout

Programming

Graphic Design

Resources

Navigation

C2D Projects

Unsystematic Affiliates

Tutorial Index Christian Cosmos Tutorials-db Tarnic 

Change Language

Who's online

There are currently 0 users and 5 guests online.

Members-system (using My-Sql)

PHP and MySQL login-system

Here I will teach you how to create a really basic login-system for use in php and mysql. The system can easily be built on to work with flash and other applications.

I'll just start:

First you need a "data.php" file that looks like this:

<?php
 
$dbc 
mysql_connect("localhost","***username***","***password***"); mysql_select_db("***db_name***"); 
session_start();
?>

You also need a database with a table (registered) with fields that look like the SQL code below. (If you want, you can copy it into phpMyAdmin and it will create the table.)

CREATE TABLE `registered` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(64) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

Then (in the main file) we need to include the "data.php"-file:

<?php
include "data.php";
?>

<?php
function loginForm(){
?>
<form method="post">
<strong>Username:</strong> <input type="text" name="login[username]" /><br />
<strong>Password:</strong> <input type="password" name="login[password]" /><br />
<input type="submit" />
</form>

<?php
   
}
?>

Now what this does, is that if we ever run the function loginForm() it will output all that HTML there (which of course just is a basic form).

Then we need to make a is_logged_in() function. The code for that should be:

<?php
   
function is_logged_in(){
       
//isset will return TRUE or FALSE
       
return isset($_SESSION['loggedIn']);
    }
?>

All this function does is to return whether or not the variable $_SESSION['loggedIn'] is set or not. If it is set - return true. If the session is NOT set - return false.

Now we need to make a function that tells us whether or not the user is trying to login.

<?php
   
function is_logging_in(){
        return isset(
$_POST['login']);
    }
?>

This will return true if the post-variable login is set (remember, we put the input field inside an array named login... name="login[username]").

Now we need a function to do the login...

<?php
   
function login($username$md5password){
       
$query 'SELECT * FROM `registered` WHERE `username` = \''.mysql_real_escape_string($username). '\' AND password = \''mysql_real_escape_string($md5password). '\'';
       
$rs mysql_query($query);
        if(!
mysql_num_rows($rs)){
            echo 
"<strong>Bad login!</strong><br />";
           
loginForm(); //here we ask the user to login again...
           
die();
        }
        while(
$row mysql_fetch_assoc($rs)){
            if(
$username == $row['username'] && $md5password == $row['password']){
               
$_SESSION['loggedIn'] = true;
                die(
"<script language=\"javascript\">window.location.reload();</script>");
            }
        }
        echo 
"<strong>Bad login!</strong><br />";
       
loginForm();
        die();
    }
?>

Than we need a function to deal with what to do is to create a function to manage what to happen if the user is logged in:

<?php
   
function loggedIn(){
        die(
"<h1>You are logged in!</h1>");
    }
?>

Ok... Now we just need to structure everything out...

<?php
   
if(is_logged_in()){
       
loggedIn();
    } elseif(
is_logging_in()){
       
login($_POST['login']['username'], md5($_POST['login']['password']));
    } else {
       
loginForm();
    }
?>

All the code now looks like this:

<?php
   
include "data.php";
    function 
loginForm(){
?>

<form method="post">
<strong>Username:</strong> <input type="text" name="login[username]" /><br />
<strong>Password:</strong> <input type="password" name="login[password]" /><br />
<input type="submit" />
</form>

<?php
   
}
    function 
is_logged_in(){
        return isset(
$_SESSION['loggedIn']);
    }
    function 
is_logging_in(){
        return isset(
$_POST['login']);
    }
    function 
login($username$md5password){
       
$query 'SELECT * FROM `registered` WHERE `username` = \''.mysql_real_escape_string($username). '\' AND password = \''mysql_real_escape_string($md5password). '\'';
       
$rs mysql_query($query);
        if(!
mysql_num_rows($rs)){
            echo 
"<strong>Bad login!</strong><br />";
           
loginForm(); //here we ask the user to login again...
           
die();
        }
        while(
$row mysql_fetch_assoc($rs)){
            if(
$username == $row['username'] && $md5password == $row['password']){
               
$_SESSION['loggedIn'] = true;
                die(
"<script language=\"javascript\">window.location.reload();</script>");
            }
        }
        echo 
"<strong>Bad login!</strong><br />";
       
loginForm();
        die();
    }
    function 
loggedIn(){
        die(
"<h1>You are loged in!</h1>");
    }
   
//here komes the logic...
   
if(is_logged_in()){
       
loggedIn();
    } elseif(
is_logging_in()){
       
login($_POST['login']['username'], md5($_POST['login']['password']));
    } else {
       
loginForm();
    }
?>


Submitted by Alxandr on August 29, 2007 - 5:32pm.
printer friendly version

automatic nav

How would you make it goto another page?

nice tut


Sessions

Just use session variables xD


unclean

if you use this script, your site will be vulnerable to sql injections via the username or password variable.


header() function can make

header() function can make it go into the main page


Register?

Nice Script, i got it to work, but how do people register into the database?

E-mail me a response, or let me know you replied...


New Login Form

This isn't a 100% bullet-proof script. It is just to show the basic idea of how these things work. Later on I will be posting my own extensive script that will be more suited to a live environment.

Here is a revision I did of this script:

<?php

   
//Include the database connection
   
include "data.php";
   
   
//In order to work with sessions we need use session_start()
   
session_start();
   

   
//Return true if the session is set
   
function is_logged_in(){
        return isset(
$_SESSION['loggedIn']);
    }
   
   
//Check to see if they posted a value called "login"
   
function is_logging_in(){
        return isset(
$_POST['submit']);
    }
   
   
//Function to show the login form
   
function loginForm(){ 
        print 
'
        <form method="post">
        <strong>Username:</strong> <input type="text" name="username" /><br />
        <strong>Password:</strong> <input type="password" name="password" /><br />
        <input type="submit" name="submit" value="Login" />
        </form>'
;
    }

   
//See if the login matches a user in the database
   
function login($username$password){
       
       
//Clean the values of XSS and Injections
       
$username trim(htmlentities(strip_tags($username), ENT_QUOTES'UTF-8'));
       
$password md5(trim(htmlentities(strip_tags($password), ENT_QUOTES'UTF-8')));
       
       
//Create the MySQL Query
       
$query 'SELECT * FROM `registered` WHERE `username` = \''.mysql_real_escape_string($username). '\' AND password = \''mysql_real_escape_string($password). '\'';
       
$result mysql_query($query);
       
       
//If we found 1 or more users that matched the login
       
if(mysql_num_rows($result) > 0) {
       
           
$_SESSION['loggedIn'] = true;
           
header("Location: "$_SERVER['PHP_SELF']);
            exit;
           
        } else {
            echo 
'<strong>Bad login!</strong><br />';
           
loginForm(); //here we ask the user to login again...
           
exit;
        }
       
    }
   
   
//Print "You are loged in" and end the script
   
function loggedIn(){
        die(
'<h1>You are loged in!</h1>');
    }
   
   
   
//Here comes the logic...
   
    //If they are already loged in
   
if(is_logged_in()){
       
loggedIn();
   
   
//Else if they have submited the form to login 
   
} elseif(is_logging_in()){
       
login($_POST['username'], $_POST['password']);
   
   
//Else this must be the first time they have come so show the login page
   
} else {
       
loginForm();
    }
?>


Feedback on member system article...

You have a point there, unclean. The user and password variables need to be run through mysql_real_escape_string, and the header functions require the exit construct after them for if the browsers do not act on the location headers.


Comment on article.

A nice login system article, although I would highly recommend the OOP approach to programming such systems. Perhaps that can come about in the next instalment :) ! Keep up the good work.

Adam @ TalkPHP.


I followed the intructions

I followed the intructions to a tee, and I have insert a username and a password in my table in the database, but it doesn't work. I try logging in with the correct username and password and it doesn't work! Could you tell me why it does this?


Try adding "print"

Try adding "print" statements after every statement. This is one way to see where in the script you are making it to. Then, if you see the WRONG print statement print you will know where to look. For example:

<?php
//If they are already loged in
if(is_logged_in()){
   
///////////////////////
   
print 'You are logged in';
   
loggedIn();

//Else if they have submited the form to login 
} elseif(is_logging_in()){
   
///////////////////////
   
print 'You are logging in';
   
login($_POST['username'], $_POST['password']);

//Else this must be the first time they have come so show the login page
} else {
   
///////////////////////
   
print 'show the login form';
   
loginForm();
}
?>


Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br> <br /> <h3>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use BBCode tags in the text, URLs will be automatically converted to links
More information about formatting options



Like what you see?

Why not add more? C2D is looking for other Christian Web Masters who would like to help write articles for this site. If you have expericance in FLASH, CSS/HTML, PHP/MySQL, PhotoShop/GIMP, Blender, Javascript, or just General Design - our users would love to hear what you have to say. Contact Us

delicious   digg   reddit   magnoliacom   newsvine   furl   google   yahoo   technorati