How to Create Login Page in PHP and MySQL with Session

==========================
Due to a lot of problem reported by friends about these script writing, so here I put the complete scripts. You can grab it here: http://rapidshare.com/files/195043222/login-frozenade.co.nr.zip
Thank you for concern. :)
==========================

The production of login page using PHP and MySQL is actually very simple.

I assume that you use local PHP connection and your MySQL database configuration use ‘localhost’ as hostname and ‘root’ as user with blank password.

First, let’s create a database:
create database dblogin;

Then use our database we’ve just created with command:
use dblogin;

Now, let’s create a table:
create table tbuser
(username varchar(50),
password varchar(255))

After that, fill the table with username ‘admin’ and password ‘adminpass’.
insert into tbuser values ('admin',md5('adminpass'));

Now, let’s prepare the login page.
<html>
<head>
<title>login page</title>
</head>
<body>
<form method="POST" action="loginproc.php">
<p>username: <input type="text" name="username" size="20"></p>
<p>password: <input type="text" name="password" size="20"></p>
<p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
</form>
</body>
</html>

Save above document with name ‘loginpage.php’.

Now, prepare a file and give it name ‘loginproc.php’ to check the validity of username and password.
<?
session_start();

$server = "localhost";
$username = "root";
$password = "";
$db_name = "dblogin";

$db = mysql_connect($server,$username,$password) or DIE("Connection to database failed, perhaps the service is down !!");
mysql_select_db($db_name) or DIE("Database name not available !!");

$login = mysql_query("select * from tbuser where (username = '" . $_POST['username'] . "') and (password = '" . md5($_POST['password']) . "')",$db);
$rowcount = mysql_num_rows($login);
if ($rowcount == 1) {
$_SESSION['username'] = $_POST['username'];
header("Location: securedpage.php");
}
else
{
header("Location: loginpage.php");
}
?>

As you see above, there is ’session_start();’.
This function is used to initializes a data session. It will creates a new session or continues previous session from data session change by GET, POST or cookie.
See the detail information about session here: http://id.php.net/function.session-start

If username and password are correct, then we’ll be directed to ’securedpage.php’.
This is a page that we want to show if login is successful. This page cannot be accessed if there is not found the correct data session when login is successfully passed. This page also contains ‘logout’ menu, so we can destroy our login data session then return to login page.

This is content of ’securedpage.php’:
<?
session_start();
if (!isset($_SESSION['username'])) {
header("Location: loginpage.php");
}
?>
<html>
<head>
<title>secured page</title>
</head>
<body>
<p>secured page with session <? echo $_SESSION['username']; ?></p>
<p><a href="logoutpage.php">logout</a></p>
</body>
</html>

Script for ‘logout.php’:
<? session_start();
unset($_SESSION['username']);
session_destroy();
header("Location: loginpage.php");
?>

Store your files you have created in one location. e.g: ‘logintest’.
So, the login page could be http://localhost/logintest/loginpage.php

So easy, isn’t it? ;)

==========================
Due to a lot of problem reported by friends about these script writing, so here I put the complete scripts. You can grab it here: http://rapidshare.com/files/195043222/login-frozenade.co.nr.zip
Thank you for concern. :)
==========================

61 Responses to “How to Create Login Page in PHP and MySQL with Session”

  1. swastik Says:

    wOw dUde..rlly cUte..nd XciTng…Thnkx a lOt..
    miss U tOOO….it will useful tO me and Others jUs hOpe…bye Tkre

    Luv nd rgrds…

    swastIk…

  2. Puneet Says:

    Thnaks Man…. Thank You Very Much for This Script… This Script Helped Me a Lot…. I have no Words… You Know I was trying to create Sessions for the Last Two Days… But You Made That Task Easy for Me..

    Thanks Buddy.. Please Keep on Adding Scripts Like This.. This Will Really Help Others.. Who are Struggling..

  3. frozenade Says:

    you’re welcome.

    it’s nice to me to able to helped other people out. ;)

  4. swastika Says:

    hy mOrning dUde..hOw r U..
    hOPe fine well..

    please pOst mE Display a Random Image..
    Thnks in advanz…

    rgrds nd lUv
    sWastik…Tkre…

  5. frozenade Says:

    i’m a little dizzy right now. :)

    which random method do you like? by determined names of files, or by all files in a folder?

    but, a little late perhaps, ’cause i’m working on my final project right now, and i shall collect it next two weeks. :D

  6. microsofttre Says:

    up to with a chunk a bit of attempt. from by themselves accomplish a real the boys the boys as proud let it go.

  7. shanmu Says:

    Hi.. frozenade ..

    Really ur Post is very useful for me..

    Thanks alot

    Continue ur post like this in future also.

  8. frozenade Says:

    hello.

    glad to know that.. :)
    thx.
    i’ll add the others soon.

  9. blackHat Says:

    For some reason when i tried this, when i tried to test the login, i just got a blank page. No errors or anything were referenced, and i was not redirected to securepage.php. It’s as if the code on loginproc.php is unreadable or something…

    Any idea why this would be?

  10. frozenade Says:

    I tested it and works well.

    what engine do you use? XAMPP, PHPTriad, etc?

  11. ajani ashish Says:

    hoe do you create login php with sql session start with javascript alert

  12. salman Says:

    hye man can you explain me how can i create login page in front page?and where i crete table?

    (create table tbuser
    (username varchar(50),
    password varchar(255)))

    i dont know about where i create this table?

  13. sivaji Says:

    This code is not secure ,it can allow sql injections .

  14. boris Says:

    hello, trying to work with sessions – but i experience sessions having a limited validity. how can you control the validity of a session?

  15. coding Says:

    Thanks very much. Your scripts are straight forward. They have really helped, i have been struggling to get something clear and easy to understand like yours. Keep on adding more.

  16. ryaganti Says:

    Thank you very much.

  17. Daniel B Says:

    Hi, this is a very good scipt. I have been browing the internet looking for a good one. I am just having a very little detail, when I run the script(loginproc.php) there is an error message saying: Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\wamp\www\Hunter\loginproc.php on line 10

    Warning: Cannot modify header information – headers already sent by (output started at C:\wamp\www\Hunter\loginproc.php:10) in C:\wamp\www\Hunter\loginproc.php on line 17
    Can some body help me out with this? Thank you in advance.

  18. Daniel B Says:

    by the way, I am using WAMP

  19. frozenade Says:

    @ajani ashish
    it’s simple, just add “alert(‘your message’)” in your javascript session.

    @salman
    use MySQL command console, open your mysql directory then run mysql.exe

    @sivaji
    Yes you’re right. This is for beginning user. For advance, you can modify this script.

    @boris
    of course you can. see the session manual to set the timing at PHP website.

    @Daniel B
    I have try this script and it’s okay.
    Make sure if you copy-paste the script from this blog, change “ sign to “. Because WordPress convert double quote to ASCII character, so it cannot be recognized. What WAMP version do you use? I use XAMPP.

  20. Daniel B Says:

    Thank you very much Frozenade for your prompt response. I am using WampServer 2 this is the latest version that it shows in the wamp website. By the way, would you recomend wamp or XAMPP.? Thank you.

  21. Daniel B Says:

    And I am using Zend 5.5.0 to create the php files. Should I use another editor.?

  22. frozenade Says:

    Hi, Daniel..

    I never try WAMP yet. But I recommend you to use XAMPP ‘coz it more comfortable to be used.

    About editor, you can use any text editor. Never mind. I use DzSoft PHP Editor and RapidPHP. They’re handy.

    You can try using XAMPP first, if you still have problem. Just report to me then I’ll send you the whole working files. ;)

  23. Steve D Says:

    Hi, All seems ok I have changed the ” characters but when I press submit on the opening form it shows the loginproc.php in the nav but when I click it just refreshes a blank loginpage.php form,

    code for loginpage.php

    login page

    username:
    password:

    Code for loginproc.php

  24. frozenade Says:

    I’ll send you the whole working files. I’ll be home on this Sunday, coz the files are in there and I am not in that place right now. But remind me ok? coz I’m forgettable.. :D

  25. jake Says:

    I too am getting a blank loginproc.php page.. also using WAMP.. any idea on what could be causing it?

  26. Chaity Says:

    Hi
    Thanks thanks thanks…

    I mvery new in php. I was in problem for login logout including session..u solve my problem..

    many many thanks…

  27. Chaity Says:

    I have a problem in my php code. I am using php 5. The problem is that when i insert some data it is inserted successfully in the database. But if i refresh the insert.php the same data is inserted again in the database. it is simple insert code. please give me solution how can i solve the problem.

  28. rini Says:

    TQ, fren!!!!

    means a lot!

    really useful for my FYP:)

  29. Emir Says:

    Thank you for this wonderful post!!

  30. praveen Says:

    hi i want to know that when one table of content in mysql is showing in another table how to solve this problem

  31. Krupesh Says:

    Hey Ive done everything you have written at the top but every time i press submit i just get a blank page :S very weird? is there any solution to this it would be very helpful Cheers Krups

  32. frozenade Says:

    Mmm.. strange. It works here.

    Okay, I’ll upload the zipped file here. ;)

  33. pankaj choudhary Says:

    how can i use session in php

  34. frozenade Says:

    Hello all friends.

    This is the download link for the script.

    Enjoy;)

    ==========================
    Due to a lot of problem reported by friends about these script writing, so here I put the complete scripts. You can grab it here:

    http://rapidshare.com/files/195043222/login-frozenade.co.nr.zip

    Thank you for concern. :)
    ==========================

  35. phpcobra Says:

    this script its not secure, it contains the connection data that now adays with injections could be easily retrieved:
    $server = “localhost”;
    $username = “root”;
    $password = “”;
    $db_name = “dblogin”;

    $db = mysql_connect($server,$username,$password) or DIE(“Connection to database failed, perhaps the service is down !!”);

    This piece of code should be written in a separate file, and included with require_once(‘connection.php’)
    so that thee datas are parsed, then….
    in order to be able to move the file from one server to the other i would use in stead a dynamic url…
    function dynamic_url($page= ‘index.php’){
    $url= ‘http://’.$_SERVER['PHP_HOST']. dirname($_POST['PHP_SELF']);
    $url= rtrim($url, ‘\\/’);
    $url.=’/’.$page;
    return $url;
    }
    //
    its true your code works, but if your form goes in wrong hands…..
    ciao

  36. frozenade Says:

    yes, you are absolutely right.
    i have put comment about this inside readme file.
    I’ll show safe way to handle login form later. ;)

    thanks for care, bro :)

  37. Septo Aji Passat Says:

    trima kasih udah ngajarin caranya!
    mudah dimengerti dan simpel

    Thanx

  38. anindya chatterjee Says:

    Thanks for the script.I have got to know a lot from it.

  39. frozenade Says:

    @Septo Aji Passat
    sama² bro ;)

    @anindya chatterjee
    you’re very welcome.. ;)

  40. Shadow396 Says:

    “blackHat Says:
    March 31, 2008 at 11:12 pm

    For some reason when i tried this, when i tried to test the login, i just got a blank page. No errors or anything were referenced, and i was not redirected to securepage.php. It’s as if the code on loginproc.php is unreadable or something…

    Any idea why this would be?”

    I m having the same problem……………

    Pls frozenade help

  41. frozenade Says:

    hmm… strange. it works fine here.

    okay, i’ll create another one. hope it works…
    please wait and come back again… :)

  42. Waqas Says:

    thanx alot simple and to the point

  43. jet Says:

    everything works fine for me… you just save my day. thank you!!!

  44. jet Says:

    @frozenade:

    one more thing… i’ve notice that after logging in, the securepage.php only shows “secured page with session” does it print a username after that line or its just a plain simple text of that? thank you!

  45. Milind Says:

    Thanks I just Implement This

  46. tunde Olaofe Says:

    Thank you for the free script code for the creating of the logging page but I have issue here which is

    Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at C:\xampp\htdocs\form\loginproc.php:6) in C:\xampp\htdocs\form\loginproc.php on line 7

    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at C:\xampp\htdocs\form\loginproc.php:6) in C:\xampp\htdocs\form\loginproc.php on line 7

    Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\form\loginproc.php:6) in C:\xampp\htdocs\form\loginproc.php on line 24

    the page can’t function properly and I have debug here I dont know where the error is from ?

  47. kk Says:

    gr8 things

  48. Shurane Says:

    For those of you having problems with the script, it’s probably because there aren’t any “php” tags. The “<?" in the beginning should say "<?php", minus the quotation marks.

    That's what I did to get it working. Maybe it's something with PHP5?

  49. Zia Says:

    Man that was ridiculously simple. Thanks alot man.

  50. frozenade Says:

    #tunde olaofe:
    make sure you dont put anything above session_start();

  51. frozenade Says:

    #jet; it prints username session. :)

  52. Sarb Says:

    Hi frozenade,

    Thanks for the script. It is a great help for me as I am just started learning PHP/MySql.

    The script worked finally with one modification. In loginproc.php file, I have to remove md5 function. I just delete md5 from the following line and bang, it worked. Is there any reason for using md5 function here. just curious. Please reply

    $login = mysql_query(“select * from tbuser where (username = ‘” . $_POST['username'] . “‘) and (password = ‘” . md5($_POST['password']) . “‘)”,$db);

    hi..

    i suggest you don’t disappear the md5 function. it’s required to keep your password secured. and to avoid a SQL injection, please append mysql_real_escape_string function in every form field post. ex: mysql_real_escape_string($_POST['username'])

    thanks ;)

  53. sam Says:

    thank you very much !!! it really helped me, coool
    needed to add (php)

  54. socoro Says:

    nice tutorial easy to understand
    p.s. I agree with Sarb >>mysql_real_escape_string

  55. Surya Says:

    Hi Frozenade!! I can’t use your script boss!! Whenever I’m giving the user name & password (whether right or wrong, after clicking “Submit”, it’s showing a blank page with address “loginproc.php”.
    Pls help me ASAP.

  56. wanie Says:

    hai..kwn2 boleh tolong sy hasilkan page login x ?

  57. wanie Says:

    sy x thu mcm mne nk hasilkan login bagi web based…please…

  58. wanie Says:

    how to update password???

  59. Jeremy Says:

    All I get no matter what I do is a blank page and it should at least give an error. This script should be laced with error warnings t figure out what the issue is. I think when it comes to logins root should not be used anyway. Sure locally on a testing server cool but the web should not use root. Starting from scratch in setting it up as it were to be used from the internet with seperate username and password would be nice as well as a register

  60. Elvis Says:

    Man, thanks a lot, so easy, so nice, and still perfect, i was able to create my perfect registration, login, logout and user managing in 15minutes!
    Instead of a securedpage with a redirect to the loginpage you could use your index with a link to the login somewhere and instead of a redirect you pass a value $log=0, something like this:

    and

    login

    logout

    where you want the link:)
    that’s just how i’ve used, still your code is the simplicity made beauty.
    See ya

  61. frozenade Says:

    hmm… it seems still difficult for some people. okay, I will update it into better one.

    stay tune.. ;)

Leave a Reply