Edmonton Web Design and Photography

Php User Login With Sessions


Posted in: Tutorials on March 7th, 2007

This is a tutorial more or less on principle for sessions with PHP. I used this chunk of code in my Address Book and Spoke Calculator. The source code is available to download and its more or less together for you to look at. its not a working micro site. the components however should work.

Here is the work flow that i used:

  • Login Form
  • Check Login against Database
  • Allow if correct information was entered.
  • Deny if wrong information was entered
  • Once Logged-in allow user to log out.
  • If some one goes to a page in history test if the session is true, if not redirect them to log in.

Note: this article has been updated to reflect some of the viewers comments and thoughts.

Step one – Log-in Form:
We need some way to take the users information and pass it on to the next script that will decide if the user may enter.

<form name="form" method="post" action="manage-check.php">
  <fieldset>
  <legend>Member Login:</legend>
  <dl>
    <dt>
      <label for="myusername">Username:</label>
    </dt>
    <dd>
      <input name="myusername" type="text" id="myusername" />
    </dd>
    <dt>
      <label for="mypassword">Password:</label>
    </dt>
    <dd>
      <input name="mypassword" type="password" id="mypassword" />
    </dd>
    <dt>
      <input type="submit" name="Submit" value="Login"/>
    </dt>
  </dl>
  </fieldset>
</form>


Step 2 – MySQL Code:

We don’t need to get into this to much its fairly simple.

DROP TABLE IF EXISTS `members`;
CREATE TABLE IF NOT EXISTS `members` (
  `id` int(4) NOT NULL auto_increment,
  `username` varchar(100) NOT NULL default '',
  `password` varchar(40) NOT NULL default '',
  PRIMARY KEY  (`id`)
);

Step 3 – Check:
Updated: This portion [sha1($_POST['mypassword'])] was added to reflect the comments posted bellow in regards to encrypting the password.

The sha1 takes data and converts it into an encrypted set of characters.

apple = d0be2dc421be4fcd0172e5afceea3970e2f3d940

So what i did was assign “$passwordHash” a new value by grabbing the password and using sha1 to get my new encrypted value.

After we submit the login information we need to search the data base and make sure that the information comes back with one user. you can have the same user name or the same password on a few users but unless its an exact match you wont get in. So we use a MySQL “SELECT”, and “WHERE” telling our script to look for a user name and password we then check the number of results returned, If its equal to 1 then its a match, If not you are rejected. We can check now many results came back by using “mysql_num_rows” this will be given a value and with a simple If statement we can see get our logic.

eg. if $numofrows==1 Then set the session, if not send them to a deny page.

In this little chunk of code we are starting a new session with the information containing our user name and password, once that is done we the redirect the user to there goal.

session_register(“myusername”);
header(“location:index.php?title=go”);

< ?php
include_once("config.php");
include_once("open-db.php");

// username and password sent from signup form
$myusername=$_POST['myusername'];
$passwordHash = sha1(strip_tags($_POST['mypassword']));

$sql="SELECT * FROM members WHERE username='$myusername' and password='$passwordHash'";
$rs = mysql_query($sql) or die ("Query failed");

// Mysql_num_row is counting table row
$numofrows = mysql_num_rows($rs);
// If result matched $myusername and $mypassword, table row must be 1 row

if($numofrows==1){
// Register $myusername, $mypassword and redirect to file success file
// Yes
session_register("myusername");
header("location:index.php?title=go");
}
else {
// No
header("location:index.pho?title=deny");
}
?>

Step 4 – Controller:
This is just as important as the checking script. Every page that is to be “Secure” has to have this piece of code in it. Its basically seeing if there is a session containing the user name set. and if so then you are safe. If not you will be bumped back to the Login page once again.

session_start();
if(!session_is_registered(myusername)){
header("location:index.php");
}

Step 5 – Log-out:
All you need to do is link to this piece of code and it will kill the session for you and bump you back to the login window.

< ?
session_start();
session_destroy();
header("location:index.php");
?>

Remember this is more fundamental and not an exact working flow here. learn from it. Don’t take it plop it in and expect everything to work. of course you are going to need to know how to create a Database and connect to MySQL. so if you can manage that im sure you can use this script.

Enjoy.

Resources:
== | means is equal to | 5==8 returns false
If
mysql_num_rows

Download Source.
Downloaded 1810 Times.
Previous:
Next:

18 Responses to “ Php User Login With Sessions ”


  1. I see some problems with this code:

    *) SQL Injection
    *) clear text passwords in the DB and session

    The “minor” problem is, that you mix business logic with the data model (SQL).
    You separated HTML from the PHP Skripts which is good, though.

    chris
    March 8, 2007

  2. What would you recommend? I will look into the SQL Injection and how to encrypt a password.

    Something else to learn :)

    Thanks for the comment!

    Adam Patterson
    March 8, 2007

  3. Hi guys,

    What about this,

    $_value)
    {
    $$_key = get_magic_quotes_gpc() ? $_value : addslashes($_value);
    }
    }

    // username and password sent from signup form
    $mypassword=md5($mypassword); // use md5 to encrypt our pass.

    $sql=”SELECT * FROM members WHERE username=’$myusername’ and password=’$mypassword’”;
    $rs = mysql_query($sql) or die (“Query failed”);

    // Mysql_num_row is counting table row
    $numofrows = mysql_num_rows($rs);
    // If result matched $myusername and $mypassword, table row must be 1 row

    if($numofrows==1){
    // Register $myusername, $mypassword and redirect to file success file
    // Yes
    session_register(“myusername”);
    session_register(“mypassword”);
    header(“location:index.php?title=go”);
    }
    else {
    // No
    header(“location:index.pho?title=deny”);
    }

    ?>

    kyle
    March 9, 2007

  4. I use a javascript to MD5 the password and send the MD5-ed password via POST to ensure that the password does not pass through the internet naked.

    The script does not need session_register(“mypassword”);
    There isn’t a logic use for password other then logging to the system.
    For everything else the username would be sufficient.

    In fact DON’T keep the password in the session if your doing this method, since the session will be open to public via /tmp/ folders.

    If you want more protection, store the IP of the user in your sessions or DB and compare with every page load. That will prevent session hijacking too.

    Gary Tay
    March 9, 2007

  5. Using JavaScript won’t really help much, only when transmitting the data through the web form. What you want to do is save the password in the database using sha1 using a char(40) instead of a varchar(65).

    When you use sha1, you know that every password hash will be a string of exactly 40 characters. Since MySQL traverese through char-fields faster than varchar-fields because of the fixed length of each record, using char will improve the performance of big tables.

    In the HTML-code, you should set maxlength to at least 255, but in general you can assume that there won’t be a password that’s more than 14 characters long. Moreover, since your username-field has a maximum length of a 100 characters, that’s probably a good place to start.

    Moving along; the manage-check.php file should have some sort of if-statement to check whether or not the user has entered all the necessary information. Something along the lines of:

    Then you should ensure that the data in the POST-fields doesn’t contain anything that we won’t like:

    However, this will depend on what characters you allow in your passwords, as it’ll translate ” into ".

    These changes might help you to create a more secure and efficient login script, that’ll save you from some unpleasant surprises.

    Håvard Hvassing
    March 10, 2007

  6. WordPress ate my PHP-code.

    Håvard Hvassing
    March 10, 2007

  7. Håvard Hvassing – Can you post a link to it?

    I am learning about this stuff, and i got this (not to hard)

    < ?php
    $str = 'apple';

    $md5 = md5( $str );
    echo ( $md5 );
    //1f3870be274f6c49b3e31a0c6728957f

    $sha1 = sha1( $str );
    echo ( $sha1 );
    //d0be2dc421be4fcd0172e5afceea3970e2f3d940
    ?>

    How do i decode the password? or do i store the encrypted word, Then when they login you take what they enter convert it to md3 or sha1 then test to see if they are the same?

    Adam Patterson
    March 10, 2007

  8. Thanks for the input every one i figured it all out now. Actually very simple. I’m going to update the article now.

    Adam Patterson
    March 10, 2007

  9. [...] of March, 2007 (Last modified: ) Håvard WWW, WWW/PHP I came across a short tutorial on how to make a session based login script, using PHP and MySQL. However, I felt that the tutorial [...]


  10. http://pl.php.net/register_globals

    that will be better when you use:

    session_start();
    $_SESSION["loggedin"] = some_value;

    Adam Bezulski
    March 12, 2007

  11. Adam Patterson:
    If your going to be using md5 or sha1 then you dont decrypt the password.

    You store the md5 encrypted password in the db, then when the user tries to log in the post script sends encrypts the pass the user typed in and sends the encrypted one and compares the two.

    mosimo
    March 15, 2007

  12. Use mysql_real_escape_string against SQL-injection!

    DeepFreeze
    May 8, 2007

  13. DeepFreeze – What sort of benefits would there be using “mysql_real_escape_string” instead of “strip_tags” don’t they doth do the same thing?

    Adam Patterson
    May 9, 2007

  14. 1st of all strip_tags obliterates anything encased in whereas mysql_real_escape_string adds the escapes to prevent SQL injection and leaves things like intact in the database.

    2nd of all strip_tags wasn’t really designed to prevent SQL injection attacks

    forcerain
    July 5, 2007

  15. did anyone notice in the sql for the database

    DROP TABLE IF EXISTS `members`;
    CREATE TABLE IF NOT EXISTS `members` (
    `id` int(4) NOT NULL AUTO_INCREMENT,
    `username` varchar(100) NOT NULL DEFAULT �,
    `password` varchar(40) NOT NULL DEFAULT �,
    PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    drop table members if exists
    then create table member if it doesn’t exits
    of course its not going to exist you just dropped it!

    fort
    February 4, 2008

  16. fort – Great observation, people are doing a tutorial and there for if they for whatever reason have a table named members may have issues. There for delete it and create a new one.

    Adam Patterson
    February 4, 2008

  17. I execute the the code and found that when I login in and click on back button from browser, it shows me again login page. Is it any method that I can prevent user to go back to login page until unless click on logout button

    Yogendra Mishra
    July 11, 2008

  18. Add this to all your pages replacing “auth_username” with your own session value.

    <?php
    session_start();
    if (!isset($_SESSION["auth_username"])) {
    require "login.php";
    exit;
    }

    r00tdigger
    September 12, 2009

Search


Archive


Subscribe