Finishing up the user login in PHP

In a previous article I covered an example of how to log a user in using an HTML form and PHP. In another article I talked some about the global SESSION variable. Now I will show you an example of how to validate the login against a MySQL database.

In the following code it is assumed that a user has posted a username and password to this web page for validation. Let’s take a look at the code:

// Check for username and password values in our POST variable
if (isset($_POST['username']) && isset($_POST['password']) && ! empty($_POST['username']) && ! empty($_POST['password'])) {
    // Sanitize the username.  We don't want to mess up our db query or inject anything hazardous
    $safe_username = mysql_real_escape_string($_POST['username']);
    // Hash the password, resulting in a 32 byte string.  A hash doesn't need to be escaped.
    $safe_password = md5($_POST['password']);
    // Run the query.  It will return a result if we have a match
    $sql = "SELECT * FROM users WHERE username = '$safe_username' AND password = '$safe_password'";
    $res = mysql_query($sql);
    // Check for a returned row
    if ($row = mysql_fetch_assoc($res)) {
        // A match was found and a row returned.  Get the user ID and store it in a session
        $user_id = $row['id'];
        // Start our session
        // Assign the user ID to the session
        $_SESSION['user_id'] = $user_id;
        // Now our user is logged in and can roam freely about the cabin (secure pages)
        // Redirect to the user's profile page
        // Halt execution of code.  We're done here.
    // Login failed.  Let the user know.
    echo("Login attempt failed.  Please try again.");

What does this do? The script takes the posted username and password and queries the database for a match. If a match is found the user’s ID is stored in the SESSION variable, and the user is redirected to their profile page. The purpose for storing the user id is so that other pages can know if the visitor is logged in, or in other words, has a session.

The profile.php page might do something like the following to be sure the visitor can see the page.

// The first thing we should do is make sure that the visitor has successfully logged in.
// Otherwise we don't want to show this page.
// Start a session
// Check for the "user_id" variable
if (isset($_SESSION['user_id'])) {
    // The user has a valid session.  We can then use the ID for various things in our web
    // application.
} else {
    // A visitor is trying to access this page without a valid session.  Bad user, bad!
    // Redirect them to the login page
    // We're done here so get out
echo("Welcome to your profile!");

And that’s it! I hope this has given you some ideas of how you might implement a user login and track that user across pages on your own site. Enjoy!