How to Build a PHP Login Form Using Sessions

John Morris
3 min readDec 9, 2017

--

First: should you use sessions or cookies?

That’s the first big question I see. In most cases, you should use sessions. There are some exceptions, but it’s usually very specific cases and at the far end of “complex” if/when you do it. Why? Session data is stored on the server and therefore is, in general, safer to work with.

Whereas, cookies are stored in the browser…

And, it’s the Wild West out there, partna!

Okay, that outta the way… let’s get into how to do this.

I just went through all this in recording my latest course, How to Create a Login Script, and always do a bunch of research to make sure I’m up to date on the latest and greatest in whatever topic.

So, the basic idea is this:

  1. User submits login form
  2. Password is verified
  3. Create a session variable
  4. Check session variable on every page load
  5. Destroy session on logout

Okay, let’s look at some code.

Login Form

Nothing special here, really. A simple form that includes username and password fields. Action parameter is left blank assuming this form submits to itself. Of course, change that if you have a processing script at a different URL that you want to use.

<form action="" method="post">
<input type="text" name="username" placeholder="Enter your username" required>
<input type="password" name="password" placeholder="Enter your password" required>
<input type="submit" value="Submit">
</form>

Process Login

Here, we do a couple things. First, we look for and grab the user data from the database based on the username submitted. Then, we verify the password submitted against the password hash stored in our database using password_verify(). Finally, we create the user session if the password is correct. It’s this session variable we’ll check on each page load going forward.

<?php
// Always start this first
session_start();

if ( ! empty( $_POST ) ) {
if ( isset( $_POST['username'] ) && isset( $_POST['password'] ) ) {
// Getting submitted user data from database
$con = new mysqli($db_host, $db_user, $db_pass, $db_name);
$stmt = $con->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_object();

// Verify user password and set $_SESSION
if ( password_verify( $_POST['password'], $user->password ) ) {
$_SESSION['user_id'] = $user->ID;
}
}
}
?>

Page

Any pages you want to “protect”, you’d want to check for the required $_SESSION variable. This is a simple example of how to do that.

<?php
// You'd put this code at the top of any "protected" page you create

// Always start this first
session_start();

if ( isset( $_SESSION['user_id'] ) ) {
// Grab user data from the database using the user_id
// Let them access the "logged in only" pages
} else {
// Redirect them to the login page
header("Location: http://www.yourdomain.com/login.php");
}
?>

Logout

Logout is pretty straight-forward. We just destroy the session, so now the $_SESSION variable won’t exist and users will be directed to log in again. Keep in mind, this also happens whenever the browser is closed because we’re using sessions.

<?php
// Always start this first
session_start();

// Destroying the session clears the $_SESSION variable, thus "logging" the user
// out. This also happens automatically when the browser is closed
session_destroy();
?>

So, that’s the basic nuts and bolts of creating a login system using PHP sessions.

If you want the full tutorial with all the source code, the little nuances of putting it together into a coherent, object-oriented application, remember me feature and full explanations of the code… then, take my full login script course.

Best part is you can get started for free on SkillShare.

Just go here to start the 2-month FREE trial: https://skl.sh/2JqFDuJ

Take the full course (plus, all my other courses).

Cancel any time before the 2 months is up…

And, you never pay a penny.

In my opinion, it’s a no-brainer.

But, up to you.

Link is here: https://skl.sh/2JqFDuJ

Later,

John

--

--

John Morris

I’m a web designer who helps other web designers with two things: 1) how to code and 2) how to market yourself so you can earn your living as a coder.