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:
<?php // 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 session_start(); // 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 header("location:profile.php"); // Halt execution of code. We're done here. exit; } // 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.
<?php // 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 session_start(); // 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 header("location:login.php"); // We're done here so get out exit; } 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!
Allowing users to login using HTML and PHP
A form is an area of a web page where your website’s visitors can enter information and submit it. They might fill out a contact form, or use a small form to login to your system. They come in handy and in many cases are a necessity. In this tutorial we will kill two birds with one stone and show you how to make a login form (I promised a login tutorial in a previous tutorial).
First, the basics. There are several different types of fields or tags that are commonly used in a form. One type, which we won’t cover here, is the input tag with a type of file. But you can learn about it here.
- <input>
- <textarea>
- <select>
An input tag can have different types, such as:
- text
- password
- hidden
- file
- submit
- checkbox
- radio
Every form opens and closes with a form tag.
<form> <!-- the form elements go here --> </form>
We won’t go into detail on each type of form element. Rather we will focus on three types of inputs that we will use in our login example: text, password, and submit.
Start by creating a new file called login.php. Copy and paste the following code inside.
<form action="login.php" method="post"> <label>Username</label> <input type="text" name="username" value="" /> <br /> <label>Password</label> <input type="password" name="password" value="" /> <br /> <input type="submit" name="submit" value="Login" /> </form>
This is our form. It contains a text field a password field and a submit button that, when clicked, sends the data off to be validated. The form tag has two parts: action and method. Our action is the page we want to send the form data to, and the method is our method of sending the information. Sending via the post method “hides” the information, whereas sending via get will pass the data as a querystring, visible in the URL. In this example we use post because we don’t want to show the user’s credentials in the URL.
The next part is to capture the data that has been posted, and then we’ll validate it. Copy and paste the following PHP code above your HTML form. Your file should now look like this:
<?php // Check for user login if(isset($_POST['submit'])){ // User is attempting login // Verify the credentials are correct if($_POST['username'] == "apple" && $_POST['password'] == "dumpling"){ // The username and password provided are correct! echo ("You have logged in successfully!"); exit; } else { echo ("Woops! You entered the wrong username and password."); } } ?> <form action="login.php" method="post"> <label>Username</label> <input type="text" name="username" value="" /> <br /> <label>Password</label> <input type="password" name="password" value="" /> <br /> <input type="submit" name="submit" value="Login" /> </form>
Run the page and try it out! Entering anything but a combination of “apple” and “dumpling” will result in failure. But entering that combination correctly will give you a thumbs up.
At this point you might want to store the user’s id in a session, and as the user moves from page to page you can check for the id. If it exists then you know they have logged in and can access secure parts of your site. You can learn about sessions here.