User login and registration system or form are very useful when we want to store information about the users of our website, its important you learn how to create one.
This applies to all areas, from educational websites where course progress and branding can be saved to e-commerce websites where information about previous purchases made by customers is stored.
With that being said, it is important that you learn how to create a PHP login form.
In this tutorial, I’m going to show you how to build or create your own PHP login and registration forms from scratch.
Create a PHP Login or Registration Form
Our first step is to create a registration form and a registration form. The forms will actually be fairly simple. Only a username, an email address, and a password are requested in the registration form.
The username and email address are unique to anyone who signs in. If someone tries to create two accounts with the same email address, you’ll get an error message telling you that the email is already in use.
Coding the Registration Form
Below you can find the HTML for creating the registration form. You should put it in a file with the name register.php.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 | <form method=”post” action=”” name=”signup-form”> <div class=”form-element”> <label>Username</label> <input type=”text” name=”username” pattern=”[a-zA-Z0-9]+” required /> </div> <div class=”form-element”> <label>Email</label> <input type=”email” name=”email” required /> </div> <div class=”form-element”> <label>Password</label> <input type=”password” name=”password” required /> </div> <button type=”submit” name=”register” value=”register”>Register</button> </form> |
The form is very simple, but we use HTML5 to do a very basic input validation. For example, if you use type=”email” users will be notified if the email address they enter is not in the correct format. Likewise, the use of the pattern attribute in the user name ensures that the user name only consists of alphanumeric characters.
Coding the Login Form
Here is the HTML for the login form. You may put the code in a file which you may call login.php.
01 02 03 04 05 06 07 08 09 10 11 | <form method=”post” action=”” name=”signin-form”> <div class=”form-element”> <label>Username</label> <input type=”text” name=”username” pattern=”[a-zA-Z0-9]+” required /> </div> <div class=”form-element”> <label>Password</label> <input type=”password” name=”password” required /> </div> <button type=”submit” name=”login” value=”login”>Log In</button> </form> |
Style the Forms With CSS
To fully Create a PHP Login Form you also need to style the form with CSS
Here is a few CSS that you may apply to these forms:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | * { padding: 0; margin: 0; box-sizing: border-box; } body { margin: 50px auto; text-align: center; width: 800px; } h1 { font-family: ‘Passion One’; font-size: 2rem; text-transform: uppercase; } label { width: 150px; display: inline-block; text-align: left; font-size: 1.5rem; font-family: ‘Lato’; } input { border: 2px solid #ccc; font-size: 1.5rem; font-weight: 100; font-family: ‘Lato’; padding: 10px; } form { margin: 25px auto; padding: 20px; border: 5px solid #ccc; width: 500px; background: #eee; } div.form-element { margin: 20px 0; } button { padding: 10px; font-size: 1.5rem; font-family: ‘Lato’; font-weight: 100; background: yellowgreen; color: white; border: none; } p.success, p.error { color: white; font-family: lato; background: yellowgreen; display: inline-block; padding: 2px 10px; } p.error { background: orangered; } |
It contains additional style rules for error messages and headers. HTML and CSS in this section can be used as the basis for your project if you create your own forms, which may require different styles and input fields.
Create the user table and connect to the database
The next step is to create a user table that stores all information about registered users. In our case, the table simply consists of four columns: an automatic increment ID, a unique user name, an email and a password.
You can use the following SQL to quickly create the table.
1 2 3 4 5 6 7 8 | CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(25) NOT NULL, `password` varchar(255) NOT NULL, `email` varchar(100) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1; |
Now, build or create a file called config.php and inpute the following code in it be able to connect to the database.
01 02 03 04 05 06 07 08 09 10 11 12 | <?php define(‘USER’, ‘root’); define(‘PASSWORD’, ”); define(‘HOST’, ‘localhost’); define(‘DATABASE’, ‘test’); try { $connection = new PDO(“mysql:host=”.HOST.”;dbname=”.DATABASE, USER, PASSWORD); } catch (PDOException $e) { exit(“Error: ” . $e->getMessage()); } ?> |
Change the name of the database regardless of the name of your database. This file is used to connect to the database.
Code User Registration
Finally, it’s time to implement the recording function. The main function of this code is to check whether the provided email is already registered. Otherwise, we enter the username, email address and password in the database.
Place the following code at the top of registration.php.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <?php include(‘config.php’); session_start(); if (isset($_POST[‘register’])) { $username = $_POST[‘username’]; $email = $_POST[’email’]; $password = $_POST[‘password’]; $password_hash = password_hash($password, PASSWORD_BCRYPT); $query = $connection->prepare(“SELECT * FROM users WHERE EMAIL=:email”); $query->bindParam(“email”, $email, PDO::PARAM_STR); $query->execute(); if ($query->rowCount() > 0) { echo ‘<p class=”error”>The email address is already registered!</p>’; } if ($query->rowCount() == 0) { $query = $connection->prepare(“INSERT INTO users(USERNAME,PASSWORD,EMAIL) VALUES (:username,:password_hash,:email)”); $query->bindParam(“username”, $username, PDO::PARAM_STR); $query->bindParam(“password_hash”, $password_hash, PDO::PARAM_STR); $query->bindParam(“email”, $email, PDO::PARAM_STR); $result = $query->execute(); if ($result) { echo ‘<p class=”success”>Your registration was successful!</p>’; } else { echo ‘<p class=”error”>Something went wrong!</p>’; } } } ?> |
The first step is to include config.php and log in. This helps us to save all the information that we want to keep on the pages.
We then check that the user clicked the Register button to submit the form and verify that $ _POST [‘register’] was configured. Always remember that saving passwords in plain text is not a good idea. For this reason, we use the password_hash () function and save this hash in our database. This special function creates a 60-character hash with a randomly generated salt.
Finally, we execute the request and check whether there is a non-zero line number for a specific email address. In this case, the user receives a message that the email address is already registered.
If there is no line with the specified email address, we enter the information provided in our database and inform the users of the successful registration process.
Implementation of the login functionality
In our last step, we wrote the code to log in to users. This time we only check the information in the database to see if the combination of username and password entered in the form is correct…
Below is the PHP code that should go at the top of the login.php.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <?php include(‘config.php’); session_start(); if (isset($_POST[‘login’])) { $username = $_POST[‘username’]; $password = $_POST[‘password’]; $query = $connection->prepare(“SELECT * FROM users WHERE USERNAME=:username”); $query->bindParam(“username”, $username, PDO::PARAM_STR); $query->execute(); $result = $query->fetch(PDO::FETCH_ASSOC); if (!$result) { echo ‘<p class=”error”>Username password combination is wrong!</p>’; } else { if (password_verify($password, $result[‘PASSWORD’])) { $_SESSION[‘user_id’] = $result[‘ID’]; echo ‘<p class=”success”>Congratulations, you are logged in!</p>’; } else { echo ‘<p class=”error”>Username password combination is wrong!</p>’; } } } ?> |
An important thing to note here is that we don’t compare usernames and passwords in one step. Since the password is actually stored as a hash, we first have to find the hash using the given username. Once we have the hash, we can use the password_verify()function to compare the password and the hash.
As soon as we have confirmed the password, we set the variable $_SESSION[‘user_id’] to the ID of this user in the database. You can also set the value of the other variables here.
Restricting access to pages
Most of the websites where users are invited to register to have some other pages where users access and store private information. You can use session variables to protect these pages. If the session variable is not configured, simply redirect users to the login page. Otherwise, show them the content of the page.
01 02 03 04 05 06 07 08 09 10 | <?php session_start(); if(!isset($_SESSION[‘user_id’])){ header(‘Location: login.php’); exit; } else { // Show users the page! } ?> |
You just have to make sure that the script initially contains session_start()
Conclusion:
In this tutorial, we learned how to use PHP to create a basic user registration and login system or form. Once you understand the basics of login and registration systems, you can create a more complex logic that allows users to reset their passwords, check their email addresses, and more.
You can also add more front-end validation using HTML5 or jQuery attributes to make the form more comfortable to use.