Skip to content
John Morris

John Morris

Developer. Freelancer. Teacher

  • Home
  • About
  • Courses
  • Blog
  • Hire
  • Contact
Menu
  • Home
  • About
  • Courses
  • Blog
  • Hire
  • Contact
Search
Close

How to Build a PHP Login Form Using Sessions

  • By John Morris
  • December 9, 2017
  • PHP Code Snippets
  • php login script, php session login

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 to keep going with this tutorial, you can on my free tutorial site here: https://johnsfreetuts.com/logintut/

Later,

John

You might also like

The Marlboro Man’s devious client-getting secret

It’s one of the problems with how available info is these days. Any Joe Schmuck can throw up a blog or a YouTube channel and

Read More »

Religious nut rants on the “cult” of freelancing

I don’t know… maybe I’m just crazy. But, the answers to these kinds of questions seem so obvious to me. Was watching a Q&A that

Read More »

Upwork may have to finally admit it was wrong

I tried to tell them. And I mean literally. A couple years back… I woke up one day to several cease and desist letters in

Read More »

Where I get all my high-end clients

This is something I yappity-yap about in my Premium Pricing for Freelancers course, but let me rap about it here a bit. Little back-story… I’ve

Read More »

Freelance secrets from an ancient Egyptian tomb

Started watching this Netflix documentary: “Secrets of the Saqqara Tomb” and it reminded me of one of the more powerful marketing principles I learned as

Read More »

How to profit from the labor shortage

I don’t talk politics a lot in here… Not because I’m not political (although, I’m really not anymore) but more because it’s infected virtually every

Read More »
Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on reddit
Reddit
Share on pinterest
Pinterest
John Morris

JOHN MORRIS

I’m a 15-year veteran of freelance web development. I’ve worked with bestselling authors and average Joe’s next door. These days, I focus on helping other freelancers build their freelance business and their lifestyles.

PrevPreviousHow to Validate (and Sanitize) User Input In PHP Using Filter_Input() and Filter_Var()
NextHow to Create an Email-Based Password Reset Feature For Your Login ScriptNext

The simple secrets to high-paying freelance clients

What makes clients willing to pay $5,000, $10,000 even $20,000 and up for your services? Download and install my mobile app and I’ll show you. It’s free. Just click the button below:

Click here to get the app

Clients Like:

Inc. Magazine Logo
Lewis Howes Logo
Ray Edwards Logo

LATEST POSTS

The Marlboro Man’s devious client-getting secret

Religious nut rants on the “cult” of freelancing

Upwork may have to finally admit it was wrong

Where I get all my high-end clients

Freelance secrets from an ancient Egyptian tomb

How to profit from the labor shortage

WHAT OTHERS ARE SAYING

Xan Barksdale

Xan Barksdale

Very professional worker who is extremely knowledgable in WordPress and Wishlist Member. I would definitely hire again.

Fionn Ross

Fionn Ross

John is an excellent teacher.

Aaron Gott

Aaron Gott

John has a particular knack for the development and training of others.

Bradley Smith

John and I have worked together on numerous projects. John is very quick and efficient and was a pleasure to work with.

Erika Swafford

Erika Swafford

John really delivers!

Bob Patterson

Not only is John a very talented programmer and developer, he is also an excellent communicator. He has a talent for taking complex subjects and communicating them in terms that anyone can understand. This is a rare combination. This ability has enabled me to take my skills and knowledge to the next level. Thank you John for for all that you do.

Lewis Howes

John is amazing at building membership sites. He converted one of my sites over from it’s existing (hardly working) platform over to the clean and simple to use WishList membership platform. I highly recommend using John and WishList for any of your membership site needs.

Jim DeJonge

Jim DeJonge

John has a relaxed and engaging manner. His advice is solid and the explanations are well thought out.

Andrew Malone

Andrew Malone

John Morris is exceptional in his ability to give focused insight into Freelancing and starting one’s business. His direct methods inspire confidence in his honesty.

Michael Skye

Michael Skye

John is a man of integrity, who gives generously of himself to projects and people he cares about.

Chris Aitken

He significantly improved my site through his expert knowledge of PHP, CSS and Javascript. Would definitely recommend John to others.

Ray Edwards

I recommend John every chance I get. If every person I worked with were as committed to excellence, punctuality, value, and unquestionable integrity… the world would be a better place. Highest recommendation.

Lori Grant

John did an outstanding job on my project. I highly recommend him and look forward to working with him on future projects.

Jason Rumley

Jason Rumley

John has a habit of over-delivering on the expectations he sets up. That’s why he’s the best.

Bobbi Raffin

Bobbi Raffin

John is top-notch and a great guy to work with.

John Morris

Hi, I’m John. I’m a freelance web developer and online teacher. I help aspiring freelance web developers go full-time as freelancers. I’m on the social media sites below and look forward to connecting with you there.

Facebook Twitter Youtube Instagram

Navigation

  • About
  • Blog
  • Tutorials
  • Courses
  • Resources
  • Podcast
  • Terms of Service
  • Privacy Policy
  • Earnings Disclaimer
  • Referral Disclaimer
  • Sitemap

Over 9+ hours of advanced freelance training from a 17-year veteran.

Why figure this stuff out all by yourself? Subscribe below and let a seasoned vet show how to get started quickly:

Click here to get the app

© 2021 IDEA ENGINE LLC. All rights reserved

Instant Access to Over 9 Hours of FREE Freelance, Side Hustle and Work From Home Training Delivered Straight to Your Mobile Phone

screenshot

Enter your name and email address below and get instant access to over 9 hours of FREE freelance, side hustle and work from home training — delivered straight to your mobile phone.

Your email address is 100% SAFE and SECURE. We’ll never rent or sell your information. You can read our Privacy Policy here.
andrew-malone.jpg

“John Morris is exceptional in his ability to give focused insight into Freelancing and starting one’s business. His direct method inspires confidence in his honesty.”

— Andrew Malone

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Accept