Php User Login With Sessions

Categories: Development

This is a tutorial more or less on principles for sessions with PHP. It’s more about the big picture and meant as a stepping stone for further exploration.

The principal behind a user login is simple, Don’t show private or secured information to non-members.

By using sessions you can:

  • Secure content from others.
  • Show custom content to members.
  • Remember user settings in a session
  • And much more!

What we will do

  1. First, we will need to log in to the site,
  2. Check to see if the login is correct,
  3. If the login was correct then we will allow access to our site, otherwise, we will deny access,
  4. If the user leaves the site after a successful login then we will allow access again without prompting for login again.

Let’s get started

I will cover the basic elements and supply my working source with this post so don’t worry if you are missing some surrounding code that might make sense.

To start off we need to create a simple database. Something simple enough to hold a user name along with a password.

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

Now that the database has been created you need to have a username and password to test against. Start off by inserting the username and password admin. Make sure the password is inserted as SHA1. If its easier to use the following SQL in your PHPMyAdmin.

INSERT INTO `members` VALUES(1, 'admin', 'd033e22ae348aeb5660fc2140aec35850c4da997');

Now that we have some credentials in the database we need a way to log in.

<form name="form" method="post" action="index.php?action=check">
    <h4>Member Login:</h4>
    <label for="username">Username:</label>
    <input type="text" name="username" />
    <label for="password">Password:</label>
    <input type="password" name="password" />
    <input type="submit" value="Login" name="Submit" />
</form>

Every page that will use sessions needs to have session_start() at the top of the page.

The form will post to another chunk of code that is in charge of checking whether or not the login was correct.

Because the password has been encrypted using SHA1 we have to encrypt the user’s input using the same method.

// username and password sent from form
$username=$_POST['username'];
$password=$_POST['password'];

$clean_username = strip_tags(stripslashes(mysql_real_escape_string($username)));
$clean_password = sha1(strip_tags(stripslashes(mysql_real_escape_string($password))));

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

$numofrows = mysql_num_rows($rs);

if($numofrows==1){
    session_register("username");
    header("location:index.php?action=yes");
}
else {
    header("location:index.php?action=no");
}

Using the $_post[] array we will capture and assign our username and password to matching variables. It is a good idea to do some cleaning on these variables. It is common for login scripts to bear the brunt of any exploits. Using strip_tags() stripslashes() mysql_real_escape_string() will help protect against these threats.

Our password must be encoded using sha1(). We will now compare the encrypted values with each other.

The SQL statement will return the results. Because the user name will be unique and the password encrypted we should be returned one row. This is important to know. If the user name existed more than once it is possible for the password to also exist more than once. This would return 2 and cause an error. In this case, none of those users would gain access.

If we logged incorrectly then we will set the session using session_register(“username”), and redirect to the secured content. If not we will deny access and send the user back to the login screen.

We could at this point set other session variables like expiry time, but that’s a little outside the scope of this basic example.

It is time to update the default login screen. Add the following code above the login screen. We have set the session variable username. so we ill see if it has been set, if it has then redirected to the secure content bypassing the login screen.

if(isset($_SESSION['username'])){
    header("location:index.php?action=yes");
}

Every secure page should have the following code testing to see if the session variable has been set.

if(!isset($_SESSION['username'])){
    header("location:index.php?action=no");
}

Using the !isset() we will only act if the session variable has not been set.

Whats next?

We can now log in, check if the login was successful acting accordingly. We have also secured our content in case a nonregistered user or user who has logged out can not gain access to the secured information.

The last thing to do is to allow the user to log out.

session_destroy();
header("location:index.php");

Now the session has now been destroyed the user will be redirected to the main login page.

session_start();
//DB Connection information
$dbname="php_sessions";
$dbuser="root";
$dbpwd="";
$host="localhost";
// Connect to the database
$cid = mysql_connect($host,$dbuser,$dbpwd);
if (!$cid) { print "ERROR: " . mysql_error() . "n";    }
mysql_select_db("$dbname") or die(mysql_error());

switch ( $_GET['action'] ) {
    case "logout":
        session_destroy();
        header("location:index.php");
    break;
    case "no":
        echo '<h2>You <strong>NOT</strong> logged in.</h2>';
    break;
    case "yes":
        if(!isset($_SESSION['username'])){
            header("location:index.php");
        }
        echo '<h2>You <strong>ARE</strong> logged in.</h2>';
    break;
    case "check":
        $username=$_POST['username'];
        $password=$_POST['password'];

        $clean_username = strip_tags(stripslashes(mysql_real_escape_string($username)));
        $clean_password = sha1(strip_tags(stripslashes(mysql_real_escape_string($password))));

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

        $numofrows = mysql_num_rows($rs);

        if($numofrows==1){
            session_register("username");
            header("location:index.php?action=yes");
        }
        else {
            header("location:index.php?action=no");
        }
    default:
        if(isset($_SESSION['username'])){
            header("location:index.php?action=yes");
        }
        ?>
        <form name="form" method="post" action="index.php?action=check">
            <h4>Member Login:</h4>

            <p><label for="username">Username:</label><br />
                <input type="text" name="username" /></p>
            <p><label for="password">Password:</label><br />
                <input type="password" name="password" /></p>
            <p><input type="submit" value="Login" name="Submit" /></p>
        </form>
    <?
    break;
    }
?>
<p><a href="index.php?action=login">Login</a> | <a href="index.php?action=logout">Log-out</a></p>

Enjoy.

Most PHP frameworks will handle session management for you adding a protective layer around your application and should be considered overwriting your own.


Adam Patterson

Adam Patterson

User Interface Designer & Developer with a background in UX. I have spent 5 years as a professionally certified bicycle mechanic and ride year-round.

I am a husband and father of two, I enjoy photography, music, movies, coffee, and good food.

You can find me on Twitter, Instagram, and YouTube!