Home and Learn: PHP Programming Course


PHP - The Login Script

 

This lesson is part of an ongoing User Authentication tutorial. The first part is here: User Authentication along with all the files you need.

For the login page, what we'll do is to get the username and password from textboxes on a form. We'll first see if the username exists in the database. If it does, then we can go ahead and check the password using an inbuilt PHP function called password_verify. If the login is successful, we can do two things: one, set up a session variable that can be used on all pages on your site. This sessions variable is used so that users who aren't logged in won't be able to see any pages, but are redirected to the login page. The other thing we'll do is to redirect a successfully logged in user to the correct page. After all, you don't want users hanging about on the login page.

So open up the script called login.php and take a look at the code. (It's one of the files you downloaded from here: scripts.)

The bottom of the page is the HTML for the user form. It's just two textboxes and a Submit button. The PHP code starts by setting up some variables:

$uname = "";
$pword = "";
$errorMessage = "";

We then get the username and password from the textboxes:

$uname = $_POST['username'];
$pword = $_POST['password'];

The connection to the server and database is the same as before (use require to get the configure file you set up, and get those constants.)

require '../../configure.php';
$database = "login";
$db_found = new mysqli(DB_SERVER, DB_USER, DB_PASS, $database );

If the database is found, then we start a prepared statement:

$SQL = $db_found->prepare('SELECT * FROM login WHERE L1 = ?');

The SQL selects all the records where the username matches the one provided:

$SQL->bind_param('s', $uname);

We then execute and see if there any results:

$SQL->execute();
$result = $SQL->get_result();

We only need to check if there is one result, as our signup page ensured that all usernames were unique.

if ($result->num_rows == 1) {

If there are no results then we can print out a message:

$errorMessage = "username FAILED";

(Although we've said "username FAILED", you probably don't want to be this explicit. The idea is to not give any clues to an attacker. So you could just say something like "Login failed". For testing purposes, though, we'd like to know why something went wrong.)

If we do get a result back then we need the full result array:

$db_field = $result->fetch_assoc();

The fetch_assoc function, remember, brings you back an array, with all positions in the array filled with a field in the database row that was returned. The $db_field variable would then look like this:

$db_field['$ID'] = an ID
$db_field['L1'] = a username
$db_field['L2'] = a password

The one we want to check is the L2 field, which contains the password:

if (password_verify($pword, $db_field['L2'])) {
}

else {
}

Inside of the IF Statement is this:

password_verify($pword, $db_field['L2'])

To check a password in a database table, you can use the inbuilt PHP function password_verify. The password_verify function needs two things: the password you want to check, and the password hash you want to check it against. For us, the password hash is in the $db_field['L2'] variable. The password inside of the $pword variable came from the textbox on the form. When you compare the two, you'll either have TRUE, the password is correct, or FALSE, the password is wrong.

If the password and username are OK, we have these three lines of code for the IF Statement:

session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");

So that a user can be remembered across different web pages, you can use something called a Session. A session is simply the time spent at a particular site or sites. You can store values with sessions, and these values will be available to all pages on the site. When you close your browser, the sessions will end. There are quite a lot of ways to use sessions, but we're only interested in saving a value so that it can be referred to across different pages.

To set up a session variable, you need to issue the session start command:

session_start( );

This starts a PHP session. To set up a session variable that you can use to store values, you use this:

$_SESSION[ ]

In between the square brackets of $_SESSION, you type the name of your variable. Like all variable names, you can call it almost anything you like. Storing values in the session variable is just the same as storing values in a normal variable:

$_SESSION['login'] = "1";

After the script runs, you'll have a session variable called 'login' that is set to a value of 1, if the user is OK. You can then use the "header" function to redirect the user to the page on your site for members, page1.php in the code above:

header ("Location: page1.php");

Notice the else part of the password_verify IF Statement. It's this:

else {

$errorMessage = "Invalid Login";
session_start();
$_SESSION['login'] = '';

}

First, we're placing a something in the errorMessage variable: Invalid Login. This will be displayed at the bottom of the HTML form. Next, we start a session and then place a blank value in the login sessions:

session_start();
$_SESSION['login'] = '';

We're using the same session name (login), but this time we set it to a blank string. If the user tries to gain access to a restricted part of the site, we'll check for a blank string. A blank string means that the user hasn't logged on successfully, so we'll redirect them to the login page.

A note of caution here. If you switch cookies off in your browser, the script above may refuse to work! This is because when you use session_start, PHP sends the browser something called a session ID. This is a long string of letters and numbers. PHP attempts to save the session ID as a cookie. But it only does this if a line in php.ini from your Apache server is set. This line:

session.use_cookies = 1

If you set this value to 0, then you should be able to log on whether cookies are set or not. The problem is, there's a good chance that you can't set this to zero. Especially if you have web hosting with someone else. The solution, in that case, is to check whether cookies are enabled or not.

You don't actually need PHP to check if cookies are enabled. You can use Javascript. Try this search string in Google:

javascript +cookies +enabled

You should then find plenty of ideas for scripts to check if cookies are enabled in the browser.

In the next part, we'll check if the user is logged in, and offer the option to logout.

<-- Back One Page | Move on to the Next Part -->

Back to the PHP Contents Page

 

Email us: enquiry at homeandlearn.co.uk