26

Create a PHP Login Form

 4 years ago
source link: https://www.tuicool.com/articles/Q732ueJ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

A user login and registration system is super helpful when we want to store information about users of our website. This applies to everything from educational websites which might store course progress and marks to e-commerce website which will store information about customers' past purchases.

In tutorial I'll teach you how to create your own PHP login and registration forms from scratch.

Creating the Login and Registration Forms

Our first step will be the creation of a login form and a registration form. The forms will actually be pretty simple. The registration form will only ask for a username, email and password. The username and email will be unique for everyone who registers. If any one tries to create two accounts using the same email address we will show them an error message letting them know that the email is already in use.

Coding the Registration Form

Here is the HTML for creating the registration form. You have to put it in a file named register.php .:

<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 basic but we do use HTML5 in order to do some very basic input validation. For instance, the use of type="email" will alert users when the email address that they entered is not in proper format. Similarly, the use of the  pattern attribute on the username will make sure that the username only consists of alphanumeric characters.

You can read the tutorial titled form input validation using only HTML5 and regex if you want to learn more about the topic.  You can also take client-side form validation to the next level with jQuery by getting you more power over the error messages that are shown and their placement as well as appearance. If you want to learn more about client-side validation, check out those posts.

Coding the Login Form

Here is the HTML for the login form. You can to put it in a file named login.php .

<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

Here is some CSS that you can apply to these forms:

* {
    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;
}

This contains some additional styling rules for error messages and headings. The HTML and CSS from this section can be used as the basis of your project when you create your own forms which might require different styling and input fields.

Creating the User Tableand Connecting to the Database

The next step is creation of a user table that will store all the information about the registered users. In our case, the table simply consists of four columns: an auto-incrementing id, a unique username, an email, and a password.

You can use the following SQL to create the table quickly.

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, create a file called config.php and write the following code in it to connect to the database.

<?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 database name to whatever the name of your database is. This file will be used to establish a connection to the database.

Code the User Registration

It is finally time to implement the registration functionality. The main function of this code would be to check if the supplied email is already registered. If it is not, we enter the username, email and password into the database.

Place the following code at the top of registration.php .

<?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 of config.php and start the session. This helps us store any information that we want to preserve across the pages.

Next, we check if the user has clicked on the Register button to submit the form by checking if $_POST['register'] has been set. Always remember that it is not a good idea to store passwords as plain text. For this reason, we use the password_hash() function and then store that hash in our database. This particular function creates a 60 character hash using a randomly generated salt.

Finally, we execute the query and check if a non-zero number of rows exist for a given email address. If they do, users will get a message saying the email address is already registered.

If no row exists with given email address we enter the supplied information into our database and let the users know that the registration was successful.

Implementing Login Functionality

In our last step, we write the code for logging users in. This time we simply check the information in the database to see if the username and password combination entered into the form is correct.

Here is the code that goes at the top of login.php .

<?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>';
        }
    }
}

?>

One important thing to note here is that we don't compare the usernames and password in a single step. Because the password is actually stored in a hashed form, we first need to fetch the hash with the help of the supplied username. Once we have the hash, we can use the password_verify() function to compare the password and the hash.

Once we successfully confirm the password, we set the $_SESSION['user_id'] variable to the ID of that user in the database. You can also set the value of other variables here.

Restricting Access to Pages

Most websites where users are asked to register generally have some other pages where users access and store private data. You can use session variables to protect these pages. If the session variable is not set, simply redirect the users to login page. Otherwise, show them the contents of the page.

<?php
session_start();

if(!isset($_SESSION['user_id'])){
    header('Location: login.php');
    exit;
} else {
    // Show users the page!
}
?>

The only thing that you have to do is to ensure the script contains session_start() at the beginning.

Final Thoughts

In this tutorial, we learned how to create a basic user registration and login system using PHP. Once you grasp the basics of login and registration systems, you can create more complicated logic that allow users to reset their password or verify their email address, etc.

You can also add more front-end validation with HTML5 attributes or jQuery to make the form more user-friendly.

If you want to speed up your web development, you can check out some of the premium PHP form scripts available from CodeCanyon.

If have have any questions related to this post, please let me know in the comments.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK