Skip to content

Download My NEW Training App

John Morris Training App

Get access all my current and future trainings directly on your mobile device. Download the app for FREE and you’ll be given instant access to all current and future trainings.

Click to Download
John Morris Training App
John Morris

John Morris

Developer. Freelancer. Teacher

  • Home
  • About
  • Courses
  • Blog
  • Contact
Menu
  • Home
  • About
  • Courses
  • Blog
  • 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

How to get more clients hiring you

There are three reason people don’t buy: They don’t want what you have They don’t believe you They don’t believe THEY can do it And,

Read More »

These Clients Desperately Need You

I’ve been a freelancer for a loooong time (15+ years). And, in that time, have gotten to know several CEOs well enough to have had

Read More »

Hack Culture Needs to Die

Anybody else tired of “hack” culture? “7 Hacks to Triple Your…” “A Secret Hack to Instantly Double Your…” “52 Little-Known Hacks to…” I asked my

Read More »

Most Freelancers Are Too Selfish and Self-Centered

Was just watching an episode of Bar Rescue. Highly recommend if you’ve never watched. Entertaining as hell AND lots of business lessons that can help

Read More »

A Simple Formula to Grow Your Freelance Business As Coronavirus Drags On

Do you want to grow your freelance business through the Coronavirus pandemic instead of merely “surviving” it? Here’s the harsh reality… In every kind of

Read More »

How Much You Should Charge As a Freelancer

No, I’m not just going to tell you to switch to fixed-price projects like everybody else seems to do. Don’t get me wrong… they’re right.

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

How to get more clients hiring you

These Clients Desperately Need You

Hack Culture Needs to Die

Most Freelancers Are Too Selfish and Self-Centered

A Simple Formula to Grow Your Freelance Business As Coronavirus Drags On

How Much You Should Charge As a Freelancer

WHAT OTHERS ARE SAYING

Oliver Wainwright

Oliver Wainwright

I’m a fan. I have completed several of John’s courses. I find him very knowledgeable and he has a great delivery.

Erika Swafford

Erika Swafford

John really delivers!

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.

Bobbi Raffin

Bobbi Raffin

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

Bradley Smith

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

Aaron Gott

Aaron Gott

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

Jim DeJonge

Jim DeJonge

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

Thabo Motsoahae

John is one of the best instructors I have come across, I learned a lot from his online tutorials.

Fionn Ross

Fionn Ross

John is an excellent teacher.

Sukh Plaha

John is a fantastic and patient tutor, who is not just able to share knowledge and communicate it very effectively – but able to support one in applying it. However, I believe that John has a very rare ability to go further than just imparting knowledge and showing one how to apply it. He is able to innately provoke one’s curiosity when explaining and demonstrating concepts, to the extent that one can explore and unravel their own learning journey. Thanks very much John!

Steve Dimmick

Steve Dimmick

John has provided expert knowledge and advice on multiple occasions that have helped me better serve my clients. John is a Rockstar!

Jason Rumley

Jason Rumley

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

Daniel Mohlendick

On the Freelancing on Upwork course: “This is by far the best course i have watched on Skillshare!! Thank you so much.”

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.

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.

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

Do you want more clients?

Subscribe below to start building your system for getting more freelance clients:

© 2019 IDEA ENGINE LLC. All rights reserved

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