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:
- User submits login form
- Password is verified
- Create a session variable
- Check session variable on every page load
- 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
This Post Has 10 Comments
Your material looks great. I’m really keen to take your online tutorial, but the reviews for skillshare are generally terrible… I’ll wait and hope you can offer your material through a more reputable service.
All my stuff is on Patreon, as well: https://johnmorrisonline.com/patreon
Very good tutorial sir, but i tried this method and it just keeps redirecting me to the same login page even after i post correct username and password….
John,
Make sure you have whatever page you want users to go to in the field.
Thanks for sharing this! Really helped a lot! Simple and straight forward!
I keep receiving a Uncaught Error: Call to a member function bind_param() on boolean using PHP7
Iearned alot
Truly helpful material
Hello John,
I am a noob, so i ask you a dumb question
Is there a way to authentificate in php, without database, just a cookie maybe… but without password?
I want a simple page, with 3 buttons. ME, MOTHER, FATHER and one link -start now-
When my father visits the first time the page, he clicks on FATHER button, this way i know that the visitor is him. Now… how many days can the server remember that he is the father? So, next time he visits, the 3 buttons are no more, as he is recognized as father
If no one is recognized, the buttons appear again.
Now, the link will be dynamic, as if the father is logged he will click on a link, my mother on another and so on.
Any ideas how this can be done? Cookie or session… ? Can you give me some tips?
good explained