Sign In | Subscribe
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Advanced PHP
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Bookmark and Share

Start Learning Now

Our free lessons will get you started (Adobe Flash® required).
Get immediate access to our entire library.

Sign up for

Membership Overview

  • Unlimited access to our entire library of courses.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lesson files for programming and software training practice.
  • Track your course viewing progress.
  • Download lecture slides for taking notes.
  • Learn at your own pace... anytime, anywhere!

User Authentication

  • User authentication is the process of validating the identity of a user. It is often used on the web to restrict certain content and/or services to user’s based on their identity.
  • PHP’s built-in session functionality can be used to provide a means of ensuring a user is authenticated and is thus allowed to access particular web content.
  • The steps involved in one method of authentication via sessions is:
    1. Authenticate a user (various methods available)
    2. Begin a session
    3. Set specific session data signifying a user is authenticated
    4. Verify the existence of the specific session data on each page before providing any content requiring authentication
  • In order to logout an authenticated user, you simply destroy a user’s session and any data associated with it.
  • A common method used to store passwords is not to store the plaintext password, but rather a hash of the password.
  • A hash is a seemingly random string of characters generated by a hash function from a password string according to a specified algorithm.
  • Hash functions have the feature that they will always return the same hash string for a particular password string.
  • PHP provides several built-in hash functions, such as:
    • sha1() – generates a 40-character hash
    • md5() – generates a 32-character hash
  • MySQL provides SHA1() & MD5() functions for use in queries as well.
  • Additional Resources:

User Authentication

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Lesson Overview 0:10
    • Lesson Overview
  • User Authentication 1:31
    • User Authentication
  • Authentication with Sessions 2:34
    • Authentication with Sessions
    • Four Steps in Authentication via Sessions
  • Using Sessions to Restrict Access 3:58
    • Using Sessions to Restrict Access
    • Coding Example: Restricted Access Area
  • Authentication Methods 5:54
    • Authentication Methods Overview
    • Coding Example: Authentication Methods
  • Logging Out 9:57
    • Logging Out
    • Coding Example: Log Out
  • Users Table 13:50
    • Users Table
    • Example: Creating a Users Table
  • Password Hashing 17:30
    • Password Hashing
    • PHP and MySQL Built-in Hash Functions: sha1 ( ) and md5 ( )
    • Coding Example: Password Hashing
  • Required Homework 24:41
    • Required Homework: 1 - 4

Transcription: User Authentication

Hello again, and welcome back to's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be covering our last topic of this course, which is on user authentication.0005

We are going to be talking about what user authentication actually is--what it means.0011

And we are going to talk about how to implement an authentication scheme in PHP, using sessions.0016

We are going to talk about different authentication methods that are available.0026

We are going to talk about that, after a user has been authenticated, and they have been (for example) logged into the admin website0032

and used it, and they want to log out--we are going to talk about that process.0038

And then, we are going to talk about setting up our database, so that we can add, in our final lesson, user authentication to our admin website.0042

So, right now, we have been having the ability to add items, view orders, update items in the store, update departments, and so forth.0052

Well, now, in our next lesson, we are going to add what you would expect for an administrator site like that.0059

We are going to add a way to log in with a username and password.0065

So, in this lesson, we are going to talk about setting up a table called Users,0069

which is going to contain information about user accounts, to be able to log in to that.0074

Related to that topic, we are going to talk about a concept called password hashing, or just hashing in general.0078

And then, we are going to go over required homework, which is going to have you set up this Users database for our final web application development lesson.0084

User authentication is used to validate the identity of a user.0093

When someone comes to your admin website and they want to add an item to the store, you want to make sure that they are the appropriate person.0098

Authentication on the Web is often used to restrict certain content (maybe you have a members-only area) and/or services.0107

For our admin website, we would only want certain people (maybe in our organization) to be able to add items to the store.0118

Authentication is a way to restrict the ability to do these different things.0126

And the most common authentication scheme (which I am sure all of you are familiar with) is to have a user provide0133

a username and password combination that uniquely identifies that user, and is a basis for saying, "This is who I am."0138

And then, after that authentication test is passed, then they get access to whatever services or content you would like to provide them.0146

What you can do in PHP is: we know about the built-in session functionality; and we can use that as a means0156

to provide restricted access to our pages (for example, provide restricted access to our admin website).0162

And the way you do that is: you go through a couple of different steps.0171

The first step would be that you would authenticate a user.0175

So, you would have a form where they would log in with their username and password, for example.0178

And when you do that, it would start a session.0183

And there are various methods that you can do to authenticate a user; we are not going to get into that just this second.0186

We are going to talk more about the session-related part of it.0191

So, let's say a user logs in, and they are authenticated; we verify that they are who they are.0194

Then, what we can do is begin a session, and then set a session variable to...maybe we have a session variable called authenticated.0199

And then, on every page that we want to restrict access to, we can just provide a test on those particular pages0207

that verifies that this particular piece of session data is available in their session,0215

because what we are saying is that they are authenticated;0223

they were able to create a session; they were able to create that session variable.0226

If, when they go to a page, they are able to access that session, that implies that they were able to successfully log in.0229

As mentioned, what you do on your particular page that you want to restrict access to is just test for the existence of a particular session variable.0241

Because, when a user is authenticated, a session gets started, and then a known variable is set;0250

what is going to happen, as we know, assuming we are using cookie-based sessions:0257

every time a user visits a restricted page (for example) they are going to pass along their session cookie.0261

That session cookie is going to give them access to session data.0266

If they have appropriately logged in, that session data will contain this variable that we are going to use as a means for authenticating.0270

So, as long as that variable is set, then we can say, "OK, you have been authenticated; we are going to give you access to this particular page."0278

If we look at this first example script for this lecture, called restrictedAccess.php, it is a page where we want to restrict access to only authenticated users.0288

So, at the beginning of the page, we start a session (or continue a session).0299

And then, we perform a simple test on the session variable authenticated.0303

And we are going to use that as our variable to test if a user has been logged in or not.0308

And so, we are running isset on the session variable authenticated.0313

If isset is true, then the authenticated variable is going to be true; if not, it is going to be false.0319

Then, in our content area, if the user is authenticated (meaning authenticated is true), we are going to output a welcome message.0323

If not, we are going to say, "You must be logged in to view this content."0330

Well, this portion of our web application (or this lecture example) doesn't have a login screen.0335

So, every time we go to this restricted access page, we are not going to be able to view that content.0338

So, if we go to version 1, and we click on Restricted Access, we are going to get 'You must be logged in to view this content.'0343

We are going to show, in a second, how to add the login form, so that you are able to see that.0349

There are a number of different ways to authenticate users.0356

You can have things like web server authentication, or you might use Apache to allow users to access different sites.0359

Another method you can do is: you can have a PHP script that a user posts, or sends GET parameters to, with a username and password.0367

And maybe those usernames and passwords are hard-coded into the script,0376

and it can just look it up and say, "OK, the username and password...if they are both this, then we will give them access to it."0379

It is not a particularly secure example, but that is one way that you could do it.0384

Another thing that you could do is: we know how to access files in PHP.0389

So, maybe a user could post a username and password to a script.0393

That script will go ahead and look them up in the file system that contains username and password combinations, and see if that exists.0396

If so, it will authenticate the user.0403

What we are going to be using for our web application: because this course is about MySQL and PHP web development,0405

we are going to store our username and password data in a database.0411

So, when we authenticate a user, we are going to be running a query on the database0415

and saying, "Does this username and password combination exist?"0419

So, we are going to be doing that against a Users table; and we are going to be implementing that in our next web application development lesson.0422

And we are going to talk a little bit more about the Users table, coming up.0431

But as far as just learning how these authentication methods...0434

We are going to implement, in this lecture example, a simple authentication method where it just checks a password--0440

that it is equal to a hard-coded value--in order to show how we can set that session variable, so that we can see the restricted access page.0445

For example, in our version 2 of our lecture example, there are two pages now.0452

We have restrictedAccess, which is going to say, "You must be logged in to view this content."0461

We haven't logged in yet; so if we click here, it takes us to a new page that we have created, called login.0464

And what we have is: we have a login script that accepts two POST variables, username and password.0469

And what it does is: it also starts a session at the beginning, because we are using sessions to control our authentication.0478

All it does is just checks that the password is equal to a hard-coded value (in this particular case, 'password').0485

So, as long as the username provides a password equal to 'password,' we are going to say, "OK, you are authenticated."0491

The way that we are going to do that is: we are going to set that authenticated session variable.0496

In this case, we are setting it equal to true.0501

It doesn't really matter what value we set it to, because all we are testing for is its existence.0503

We go ahead and set the authenticated session variable to true.0509

And then, we are going to redirect the user, after they have logged in to that restricted access page.0512

What is going to happen is: the session has been created, assuming they provided the password equal to 'password.'0517

They created the authenticated session variable; they are redirected to restrictedAccess.php,0523

which, at the beginning, opens a session and tests to see if that variable is set.0529

Since it is now going to be set, when the user is forwarded to this page, it is going to check if it is authenticated.0534

Now, you are going to be authenticated, and you are going to get the Welcome message,0543

as opposed to saying that you are not allowed to see the restricted data.0546

In our login page, it doesn't really matter what username we put in, because all we are checking for, in this particular case, is a password.0552

I'm entering the password 'password,' and if you notice, here, it is covered up by these black dots,0560

but you have seen it, for sure, in a web application you have gone to; and that is just a special type of input field called password.0567

It doesn't actually encrypt the password, but it is something so, if somebody is looking over your shoulder, they can't see it.0574

If I go ahead and click Log In, what it is: it went ahead and validated that I provided the password 'password.'0579

It created the session variable, redirected me to restricted access, and it says, "You are now in the restricted area; welcome!"0588

The other process that involves authenticating the user is: what do you do when the user is done with the session?0600

We have all been to websites where you log in; you perform some actions; and then you log out.0605

So, that way somebody else that comes in to the computer can't just go up and have access to your data.0610

If they wanted to do that, they would have to re-log in, which would be to re-authenticate.0617

We are going to...the logout procedure is cancelling an authentication, and the way that you can do that is by simply destroying a user's session.0623

And the reason that that works is that the test that we are using on our restricted pages is just to test for the existence of a particular session variable.0632

If that user's session has been destroyed, that variable is no longer going to exist, so they are not going to get access to those pages anymore.0641

If we look at a new version of this lecture example, version 3 (let me just clear any cookies that we have),0649

if we try to go to the restrictedAccess page, it will say, "You must be logged in; click here to log in."0665

This script works the same as in the last example; as long as 'password' is provided as the password, it is going to log you in.0672

It is going to say you are welcome to the restricted area.0681

And now, it is going to have a button that is just going to go to logout.php.0683

Well, all logout.php does is destroys our session.0687

And if we look at logout.php, we can see that it starts the session, and it goes through the four-step process0690

that we talked about when we learned about destroying sessions, in a previous lesson.0697

It starts a session; it goes ahead and deletes all the session variables by setting SESSION equal to the empty array.0701

It goes ahead and deletes the session cookie.0708

It does that by using the setCookie function and setting it to a time in the past.0712

Then, it calls the session_destroy method, which, after the script is over, is going to delete all of that session data on the server.0719

Because we have destroyed...and this is actually one of the reasons why, when we learned about destroying sessions,0724

we set the session variable equal to the empty array--because, when we call the session_destroy,0729

that doesn't actually destroy the session data until after the script has ended.0738

If we were to leave out this deletion of the session variables up here, now we have a test to see if the user is authenticated or not.0743

If we hadn't deleted it, this would still show up as "the user is authenticated."0755

So, we have gone ahead and set it to the empty array, so the user is no longer authenticated.0760

In this particular case, authenticated is going to evaluate to false.0766

And then, we say, "As long as 'the user is authenticated' is false, that means the user was successfully logged out."0769

We have output a message that was logout; if not, we are going to say, "There was an error logging you out."0775

And that would happen, for example, if we had this commented out.0780

When we click on this link to logout.php, it is going to go ahead and destroy the session.0785

Let me bring up Firebug, so you can see the deletion of the cookie.0791

Click here to log out; you are successfully logged out.0798

We can see that it has a setCookie method that deletes that PHPSESSID cookie.0802

Now, because we are logged out, just to verify, let's say we tried to go to restrictedAccess.php again.0809

When we try to do that, it is going to try to access that session variable, authenticated, which no longer exists, because our session is destroyed.0817

And we are going to get the message that says, "You must be logged in to view the content."0823

And so, that is how the logout works.0826

The way we are going to authenticate--now that we have learned about how authentication works and how to use it during sessions--0831

we are going to talk about the authentication method that we are going to use for our web application,0837

which is to use authentication from a MySQL database.0841

We are going to be creating a table called Users, and it stores information about admin users for our administrative website.0844

It is going to be defined by this SQL statement here.0851

It is going to have four different columns: one for username, one for password, one for firstName and lastName.0854

So, we are going to allow it to set the first name and last name of a user, and then the username and password that they are going to log in as.0861

We have noted the username as the primary key, and you will notice that is not an auto-incremented integer column, like we have been using.0866

And we could denote it as a primary key, because we want to have a usernames be unique for our admin users.0873

And so, we can denote that as a primary key.0881

So, if somebody tries to create an account for a username that already exists, they are not going to be able to do that.0882

Now, one thing to note is that this is set as a VARCHAR, which means it can have a username up to 20 characters in length.0888

These are variable-length strings for firstName and lastName.0894

However, for password, we have set it to a fixed-length string of 40.0897

And we are going to talk about that in the next slide.0900

And the reason for that is that we are going to use that to store our password.0902

And we are going to be storing it in a special format.0906

Let's go ahead and create this Users table: I'm just going to type the CREATE TABLE statement.0909

Our primary key is going to be username, which is going to be a VARCHAR that (to review) is 20 characters in length.0922

So, it can be a 20-character username.0934

A password: as mentioned, it is going to be a fixed-length field of 40 characters--we are going to see why in a second.0941

firstName: we are going to allow them to have up to 15 characters for their first name0948

(let's double-check that), and then 20 characters for their last name.0953

So now, we have created our Users table.0964

And that is what the structure of the table looks like.0975

Let's say we want to add a user to our database.0977

So, INSERT INTO Users VALUES...we are going to provide a username jsmith, and we are going to have him use the password...0983

in this particular case, let's just say 'password'...well, let's pick something more unique: maybe his wife's name will be his password--jenny.0996

His name will be firstName Joe, lastName Smith; we can insert that into the table.1008

Now, when we view the content of our Users table, we can see that we have a user named Joe Smith: password jenny, firstName Joe, lastName Smith.1016

Well, as you can see, our password here is stored in plain text, meaning anybody that can view our database can view everybody's password.1028

So, they would be able to have access to their account, and that is a security risk.1036

So, what we are going to talk about in our next slide is how to obscure that, so that anybody that looks at the database--1040

if the database were to be compromised, they wouldn't be able to find out everybody's username.1045

And the way we are going to do that is through a method known as hashing.1051

And what it is: a hash is essentially a random string of characters that is generated by a function.1055

What you do is pass a password to a hash function.1066

It runs some algorithm, and that algorithm will generate a random string.1069

The feature of a hash function is that, every time you pass it the same string, it is always going to generate the same output.1074

So, what we can do is: when a user creates a password, we can run a hash function1081

that is going to generate the same key for that password every time it is entered.1087

We store the hash in the database, which is going to be random strings; it is going to be this long, ugly-looking string.1091

And then, the way we would authenticate our user is: when they type in their password,1098

we run the hash function on the plain text password they entered, and then compare the two hashes,1101

because we know that the hash is always going to be the same for the same username.1107

And the other thing about the hash is that they are generally unique; it is very hard to have two strings that would generate the same hash.1111

So, the chances of two passwords having the same hash value is very unlikely.1119

Well, PHP provides two built-in hash functions that use two different algorithms.1124

One is called sha1, and what that does is generates a hash of 40 characters in length.1129

And there is an md5 hash, which generates a 32-character hash string.1134

We are going to be using the more secure sha1 to do that.1141

And so, when we have our PHP code (and we are going to see this in our next web application lesson),1147

when we insert a user, we are going to be running this sha1 function in PHP on whatever password string the user provided.1154

And it is going to generate the hash.1164

We have a script here called hashExamples.php that shows as we are running the sha1 function on the string 'password.'1168

And then, we are also running the md5 hash function on the word 'password' so you can see what a hash looks like.1180

When we run this particular script, we can see that they generate these really difficult strings that would be hard for somebody to look at and remember.1188

So, for sha1, it generates a 40-character string, and this is what it looks like for password.1205

And it does that every time you pass the password.1211

The md5 hash function generates a 32-character string that looks like this.1213

And so, that is what we are going to be storing in our database.1217

Now, what MySQL does is: they have analogs of those functions.1222

They have a function built in called sha1 and md5 that do the same exact thing.1226

Because these are defined algorithms, the sha1 function for MySQL is going to generate the same hash value for a password as the sha1 in PHP does.1232

For example, one of the things you can do in MySQL (if we haven't talked about it) is that you can just run some functions.1244

So, if we run sha1 on the string 'password,' we can see that it generates the string 5baa61e4.1252

Well, if we look back at our hash example: 5baa61e4, and so on; so, it generates the same password.1266

What we are going to do to get an initial account set up in our Users table is: we are going to add an admin account.1273

So right now, we can see that we have this one user in our database called Joe Smith,1282

which we are actually going to delete, because it is insecure with the password the way that it is.1288

We can see that there are no more users in that database.1295

And now, we are going to insert an admin account into the Users table.1298

We are going to have the username be admin; we are going to have the password be the empty string.1310

That is not necessarily a secure thing, but we are going to use it to be able to get our account set up.1317

We will use this to initially log into our (now it's going to be) authentication-protected admin site, to create new accounts.1327

And then, we can get rid of this account.1336

And the way we do that is: we are going to run the sha1 function on the empty string password.1337

We are going to call the user...we will give it the firstName site, for example, and the lastName administrator.1345

It looks like I had an error in the code.1358

And now, when we run a SELECT query on Users, we can see: we have an admin user, firstName site, lastName administrator.1366

And we can see that their password is this 40-character hash that is quite ugly.1373

So, anybody looking at the database won't be able to just look and see, "OK, the admin's username is admin" or "the empty string."1377

And that is why we made this field equal to 40 characters long--because that sha1 function returns a 40-character string.1385

Oh, and one other thing: just to validate that our admin account works, what we can do is:1394

we can run a SELECT query on this Users table, which is what we are going to be doing our web application to validate a user,1404

and say, "Does a user exist with the username admin and the password equal to the empty string?"1409

And if it returns a row, that means yes.1416

And the way that we are going to do that is: we are going to say,1418

"Select all of the columns from the Users table," and then we are going to provide a WHERE clause:1421

"where username equals," in this particular case, "admin, and password equals"1429

not the empty string, but equals the sha1 hash of the empty string.1439

And if we run that, we see that we get one row.1452

If we had just run it with the password equal to the empty string, we are going to get empty set, and we are not going to see that it is used.1455

Now, here we have used the sha1 within our SQL query; we are actually going to be calculating it in our PHP statement.1462

So, when we run this query, this sha1 function is going to be replaced with the hash generated by the sha1 function in PHP.1470

For the required homework for this: it is just to get that Users table set up for use in our last web development application lesson.1482

Just create the Users table, as we had demonstrated in this lecture, with the different fields that we provided.1490

Make sure that the password column is a fixed-length character string of length 40,1495

because we are going to be using the sha1 function in PHP to generate our password hashes.1502

And then, go ahead, like we did, and generate an administrator count with the username admin, and a password equal to the empty string.1507

You can call it whatever you want; you can put your name, if you need to.1514

You are going to need to use the sha1 function that MySQL provides to be able to create that hash,1518

because if you just said, "Run the INSERT statement with just the empty string,"1524

it is not going to generate that hash, and you will actually have the empty string showing up in your database.1528

So, make sure you use this function.1534

And also, the password is just the empty string, but the value that you are going to be storing1537

in that password field is going to be the sha1 output of the empty string.1542

So, it is going to be that 40-character hash.1546

And then, like we did, run a SELECT query on this new admin account that you created,1548

to verify that you can retrieve that row, using the username admin and password empty string.1555

And so, you are going to be running the query, just like we did here.1561

And that is going to verify that everything is set up and works correctly.1564

That ends today's lesson; thank you for watching, and I look forward to seeing you next time.1569