How To Create A PHP Registration System For Your Website

Are you looking to integrate PHP registration system? In this post, we create a sign-up form, validate email against the database. On successful registration of a user, we send an activation link to the user email. Once, the user clicks the activation link from the email, we will activate their account.

Having said that, let’s create our PHP registration system.

Create A users Table In The Database

For every registration system, we need a database table. Against this table records, we check whether user entering a unique email address or not. If the user details are unique and correct then only they can register to our system.

Run the below query to your database to create the table called ‘users’.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `fullname` varchar(255) NOT NULL,
 `email` varchar(255) NOT NULL,
 `password` varchar(255) NOT NULL,
 `activation_key` varchar(255) NOT NULL,
 `status` enum('0','1') NOT NULL DEFAULT '0',
 PRIMARY KEY (`id`)
) ENGINE=MyISAM;

Create A Sign-up Form

PHP Registration System

We use the Bootstrap Framework to design our registration form. Create a ‘index.php’ file and place the below code in it.

<!DOCTYPE html>
<html>
    <head>
        <title>Registration Form</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <h3>Registration Form</h3>
                    <?php if(!empty($arr_message['msg'])) { ?>
                        <div class="alert <?php echo $arr_message['class']; ?>"><?php echo $arr_message['msg']; ?></div>
                    <?php } ?>
                    <form method="post">
                        <div class="form-group">
                            <label for="exampleInputFullname">Full Name</label>
                            <input type="text" class="form-control" id="exampleInputFullname" name="fullname" placeholder="Full Name" value="<?php if(isset($fullname)) echo $fullname; ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="exampleInputEmail1">Email address</label>
                            <input type="email" class="form-control" id="exampleInputEmail1" name="email" placeholder="Email" value="<?php if(isset($email)) echo $email; ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="exampleInputPassword1">Password</label>
                            <input type="password" class="form-control" id="exampleInputPassword1" name="password" placeholder="Password" required>
                        </div>
                        <div class="form-group">
                            <label for="exampleInputPassword2">Confirm Password</label>
                            <input type="password" class="form-control" id="exampleInputPassword2" name="cpassword" placeholder="Confirm Password" required>
                        </div>
                        <button type="submit" name="submit" class="btn btn-default">Submit</button>
                    </form>
                </div>
            </div>
        </div>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </body>
</html>

Above code will display sign-up form when we run the ‘index.php’ file. You observe the variable $arr_message[‘msg’] in code which will print sign-up error if any. This variable is declared shortly.

Server Side Code For PHP Registration System

At this stage, we are ready with the sign-up form and database table. Next, on the form submit we have to write PHP code which checks whether email already exists in the database. If email exists then we throw the error message. If all details are correct, we insert the user details in the database and send an activation link to their provided email address.

Create a file ‘config.php’ where we store the database credentials.

<?php
$conn = new mysqli('DB_HOST', 'DB_USER', 'DB_PASSWORD', 'DB_NAME');

if ($conn->connect_errno) {
    echo "Error: " . $conn->connect_error;
}
?>

In our ‘index.php’ before the start of html tag add the below code.

<?php
require_once('config.php');

$arr_message = [];
if (isset($_POST['submit'])) {

    $_POST = array_map('trim', $_POST);
    extract($_POST);

    if (!empty($fullname) && !empty($email) && !empty($password)) {
        
        if ($password == $cpassword) {
            $sql = "SELECT id FROM users WHERE email = '".$conn->real_escape_string($email)."'";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                $arr_message = [
                    'class' => 'alert-danger',
                    'msg' => 'Email already exist.',
                ];
            } else {
                $email = $conn->real_escape_string($email);
                $activation_key = sha1(mt_rand(10000,99999).time().$email);

                $sql = "INSERT INTO users(fullname, email, password, activation_key) VALUES('".$conn->real_escape_string($fullname)."', '".$email."', '".md5($conn->real_escape_string($password))."', '".$activation_key."')";
                $conn->query($sql);

                //send activation link in an email
                $subject = 'Activate Your Account';
                $message = 'Hello '.ucwords($fullname).',<br> 
                            <p>Click the below link to activate your account.</p>
                            <a href="YOUR_PROJECT_URL/activate.php?key='.$activation_key.'">Activate Account</a><br><br>
                            Thanks,<br>Admin';

                $headers[] = 'MIME-Version: 1.0';
                $headers[] = 'Content-type: text/html; charset=iso-8859-1';
                mail($email, $subject, $message, implode("\r\n", $headers));

                $arr_message = [
                    'class' => 'alert-success',
                    'msg' => 'We have sent an activation link to your email. Please activate your account.',
                ];
                $fullname = $email = '';
            }
        } else {
            $arr_message = [
                'class' => 'alert-danger',
                'msg' => 'Password mismatch.',
            ];
        }
    }
}
?>

Here while storing the password we use the PHP method md5 assuming you stored the password by using this algorithm.

activate.php File To Activate Your Account

Now, it’s time to create ‘activate.php’ file. This file handles the account activation code. We write a code to activate the user account if the URL contains a correct activation key.

‘activate.php’ file contains the below code.

<?php
require_once('config.php');

if (!isset($_GET['key']) || empty($_GET['key'])) {
    header('Location:index.php');
}

$sql = "SELECT id, status FROM users WHERE activation_key = '".$_GET['key']."'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    if ($row['status']) {
        $arr_message = [
            'class' => 'alert-success',
            'msg' => 'Your account is already activated.',
        ];
    } else {
        $sql = "UPDATE users SET status = '1' WHERE id = ".$row['id']." AND activation_key = '".$_GET['key']."'";
        $conn->query($sql);

        $arr_message = [
            'class' => 'alert-success',
            'msg' => 'Your account is activated. You can <a href="YOUR_PROJECT_URL/login.php">login now</a>.',
        ];
    }
} else {
    $arr_message = [
        'class' => 'alert-danger',
        'msg' => 'Invalid URL.',
    ];
}
?>

To display the success/error message on ‘activate.php’ file add the below HTML code in it.

<div class="container">
        <div class="row">
            <div class="col-md-6">
                <?php if(!empty($arr_message['msg'])) { ?>
                    <div class="alert <?php echo $arr_message['class']; ?>">
                        <?php echo $arr_message['msg']; ?>
                    </div>
                <?php } ?>
            </div>
        </div>
    </div>

You may also want to read our related article on How To Create PHP Login System.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *