Create Complete User Registration Form in PHP and MySQL

User registration and login php mysql
User registration and login php mysql
Spread the love, Share this Article!

Subscribe to Our YouTube Channel!

Introduction – PHP User Registration Form

Do you want to create a complete user registration form in PHP and MySQL programming? and then this blog post is exactly for you. This article will show you how you can create a complete login and user registration system using PHP and MySQL programming. This tutorial includes the complete step-by-step process to create a user registration form in PHP and MySQL.

In addition, this tutorial also contains the source code of all the files to make a login and registration form in the PHP and MySQL databases. Similarly, there are many other server-side languages that we can use to create the store the user’s data and user registration details, but in this article, we are specifically using the PHP with MySQL database to create a simple user login and registration form in PHP.

What You Will Learn?

As stated previously, in this article, you are going to learn the following important concepts while creating the complete user registration form in PHP and using the MySQL database.

  1. How to create a user registration form in HTML and CSS?
  2. How to create a new MySQL database in PHPMyAdmin?
  3. How to connect with MySQL database with PHP?
  4. How to do registration form validation in PHP?
  5. Password encryption or password hashing in PHP?
  6. How to insert or update user data into the database table?
  7. How to use $_session variable in the PHP user registration and login form?
  8. How to set the cookies variable in PHP for user registration?
  9. How to create a User logout PHP code?
  10. How to create a user login system in PHP?
  11. How to write PHP code for the user login form?

Video Tutorial – Login Register PHPO

Meanwhile, You can watch the following video tutorial which includes the step-by-step process to create a complete user registration form using PHP and MySQL databases.

How to create a complete user registration form using PHP and MySQL

Steps – Login and Register for PHP Form

More importantly, to create a complete user registration system in PHP and MySQL, we are going to adopt the following approach. First of all, we are going to create the following PHP files:

  1. Create an index.php file. This file contains the HTML and CSS code for the user Sign up form.
  2. Create a new MySql database in PHPMyAdmin and a new user table where you want to store the user login details.
  3. Create a linkDB.php file. This file will contain MYSQL database connection PHP code.
  4. Create a server.php file. This file will contain all server-side PHP and MYSQL database codes for user registration and user login forms. This file is linked with both, index.php and login.php files using the PHP include function.
  5. Create a LoggedInPage.php file. This will be your home page, and after the successfully logged user in, will redirect to this home page.
  6. Create a login.php file. This file contains the login form HTML and CSS code.

How to Run PHP Code on Your Computer?

As you know that PHP and MySQL are server-side languages. You need a web hosting live server or localhost to run PHP and Mysql codes. There are two ways to execute the PHP code on your computer to create a complete user registration and login system.

  • Buy a web hosting account. Host your PHP files in your web hosting cPanel account inside the File Manager > public_html folder.
Cpanel web hosting file manager to upload files
Cpanel web hosting file manager to upload files
  • Make your computer a Local Server. Install a XAMPP application on your computer and place your PHP files inside the htdocs folder which is located at the following location on your computer.

C:\xampp\htdocs

After installation of XAMPP, you need to start the XAMPP control panel to run the PHP code on your local server. Start MySQL and Apache modules and wait for the green color indication to properly start the XAMPP local server.

XAMP control panel window
XAMP control panel window

How to Create a new PHP Database with MySQL?

To create a complete registration and login form in PHP and MySQL first, you need to create a PHP Database and user table where you want to save the customer’s details. If You don’t know how to create the new PHP database in PHPMyAdmin then you can watch the below video tutorial.

Source Codes and Explanations

This section explains the source codes of all files to create the complete user registration form using PHP and MySQL databases.

1. Source Code – (index.php File)

The following HTML CSS source code belongs to the index.php file. This code is for the user registration form in PHP.

<!-- PHP command to link server.php file with registration form  -->
<?php include('server.php'); ?>

 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Registration</title>

     <!-- CSS Code -->
     <style>
         .container{
             justify-content: center;
             text-align: center;
             align-items: center;
         }
         input{
             padding: 5px;
         }
         .error{
             background-color: pink;
             color: red;
             width: 300px;
             margin: 0 auto;
         }
     </style>
 </head>

 <body>
 <div class="container">
     <h1>User Registration System</h1>
     <h4><a href="loggedInPage.php">Home Page</a></h4>
    
     
     <div class="form" id="signUp">
     <form method="POST">
        <div class="error"> <?php echo $error ?> </div>

            <!--------- To check user regidtration status ------->
     <p>
         <?php
            if (!isset($_COOKIE["id"]) OR !isset($_SESSION["id"]) ) {
             echo "Please first register to proceed.";
            }
         ?>
        </p>
       <input type="text" name="name" placeholder="User Name"> <br> <br>
       <input type="email" name="email" placeholder="Email"> <br><br>
       <input type="password" name="password" placeholder="password"><br><br>
       <input type="password" name="repeatPassword" placeholder="Repeat Password"><br><br>
       <label for="checkbox">Stay logged in</label>
       <input type="checkbox" name="stayLoggedIn" id="chechbox" value="1"> <br><br>
       <input type="submit" name="signUp" value="Sign Up">
       <p >Have an account already? <a href="logIn.php">Log In</a></p>
      </form>
     </div>
 
 </body>
 </html>

Explanation – User Registration in PHP

The index.php file includes the HTML CSS code to create the user registration form to sign the user in. The form method is POST, which will post the data into the database. The $_cookie and $_session variables are used to check the registration status of the user.

2. Source Code – (login.php File)

The login.php file includes the following HTML CSS source for user login in PHP.

<!-- PHP command to link server.php file with registration form  -->
<?php include('server.php'); ?>

 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>User logIn</title>

     <style>
         .container{
             justify-content: center;
             text-align: center;
             align-items: center;
         }
         input{
             padding: 5px;
         }
         .error{
             background-color: pink;
             color: red;
             width: 300px;
             margin: 0 auto;
         }
     </style>
 </head>
 <body>
 <div class="container">
     <h1> User Registration System</h1>

     <h4><a href="loggedInPage.php">Home Page</a></h4>
                      <!--------log in form------>

     <div class="logInForm" id="logIn">
     <form method="POST">

     <!-- To show errors is user put wrong data -->
        <div class="error"> <?php echo $error2 ?> </div>

        <!-- To check the user loged In status -->
        <p>
         <?php
            if (!isset($_COOKIE["id"]) OR !isset($_SESSION["id"]) ) {
             echo "<p>Please first log in to proceed.</p>";
            }
         ?>
       </p>

       <input type="email" name="email" placeholder="Email"> <br><br>
       <input type="password" name="password" placeholder="password"><br><br>
       <label for="checkbox">Stay logged in</label>
       <input type="checkbox" name="stayLoggedIn" id="chechbox" value="1"> <br><br>
       <input type="submit" name="logIn" value="Log In">

       <!-- User registration form link -->
       <p>Not a register user <a href="index.php"> Create Account</a></p>
     </form>
     </div>
 </div>

 </script>
 
 </body>
 </html>

Explanation – User Login in PHP

This is the user login form in HTML and CSS. The first PHP include command is to link the server-side PHP code file with a user login form. This user login form has a link to the user registration form. Users can easily switch between login and sign-up pages.

Recommended for You!

3. Source Code – (linkDB.php File)

The linkDB.php includes the following PHP code.

<?php
// Open a new connection to the MySQL server
$linkDB = mysqli_connect("localhost","my_user_name","my_password","my_db_name");  
  if (mysqli_connect_error()){ //for connection error finding
  die ('There was an error while connecting to database');
  }
    ?>

Explanation – Connecting to MySQL Server

The above PHP opens a new connection to the MySQL database server. You have to link this file to every PHP file on your website by using the PHP include function to connect with the database server. The mysqli_connect() PHP function opens a new connection to the MySQL server.

4. Source Code – (server.php File)

The following back-end code for the user registration form in PHP will include in the server.php file:

<?php 
session_start();
//------ PHP code for User registration form---
$error = "";
if (array_key_exists("signUp", $_POST)) {

     // Database Link
    include('linkDB.php');  

    //Taking HTML Form Data from User
    $name = mysqli_real_escape_string($linkDB, $_POST['name']);
    $email = mysqli_real_escape_string($linkDB, $_POST['email']);
    $password = mysqli_real_escape_string($linkDB,  $_POST['password']); 
    $repeatPassword = mysqli_real_escape_string($linkDB,  $_POST['repeatPassword']); 
    
    // PHP form validation PHP code
    if (!$name) {
      $error .= "Name is required <br>";
     }
    if (!$email) {
        $error .= "Email is required <br>";
     }
    if (!$password) {
        $error .= "Password is required <br>";
     } 
     if ($password !== $repeatPassword) {
        $error .= "Password does not match <br>";
     }
     if ($error) {
        $error = "<b>There were error(s) in your form!</b> <br>".$error;
     }  else {
      
        //Check if email is already exist in the Database

        $query = "SELECT id FROM users WHERE email = '$email'";
        $result = mysqli_query($linkDB, $query);
        if (mysqli_num_rows($result) > 0) {
            $error .="<p>Your email has taken already!</p>";
        } else {

            //Password encryption or Password Hashing
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT); 
            $query = "INSERT INTO users (name, email, password) VALUES ('$name', '$email', '$hashedPassword')";
            
            if (!mysqli_query($linkDB, $query)){
                $error ="<p>Could not sign you up - please try again.</p>";
                } else {

                    //session variables to keep user logged in
                $_SESSION['id'] = mysqli_insert_id($linkDB);  
                $_SESSION['name'] = $name;

                //Setcookie function to keep user logged in for long time
                if ($_POST['stayLoggedIn'] == '1') {
                setcookie('id', mysqli_insert_id($linkDB), time() + 60*60*365);
                //echo "<p>The cookie id is :". $_COOKIE['id']."</P>";
                }
                 
                //Redirecting user to home page after successfully logged in 
                header("Location: loggedInPage.php");  
            
                }
            
            }

        }  
    }

      //-------User Login PHP Code ------------

if (array_key_exists("logIn", $_POST)) {
    
    // Database Link
    include('linkDB.php'); 

      //Taking form Data From User
      $email = mysqli_real_escape_string($linkDB, $_POST['email']);
      $password = mysqli_real_escape_string($linkDB,  $_POST['password']); 
      
      //Check if input Field are empty
      if (!$email) {
          $error2 .= "Email is required <br>";
       }
      if (!$password) {
          $error2 .= "Password is required <br>";
       } 
       if ($error2) {
          $error2 = "<b>There were error(s) in your form!</b><br>".$error2;
       }
       
      else {        
          //matching email and password

            $query = "SELECT * FROM users WHERE email='$email'";
            $result = mysqli_query($linkDB, $query);
            $row = mysqli_fetch_array($result);
        
            if (isset($row)) {
                
                if (password_verify($password, $row['password'])) {

                    //session variables to keep user logged in
                    $_SESSION['id'] = $row['id'];  

                      //Logged in for long time untill user didn't log out
                    if ($_POST['stayLoggedIn'] == '1') {
                    setcookie('id', $row['id'], time() + 60*60*24); //Logged in permanently
                    }

                    header("Location: loggedInPage.php");

                } else {
                    $error2 = "Combination of email/password does not match!";
                     }
  
            }  else {
                $error2 = "Combination of email/password does not match!";
                 }
        }
}
?>

Explanation

Indeed, every PHP page on the website should start with session_start(); function. This will keep the user logged in on all pages. mysqli_real_escape_string PHP function is used to get the form data from the user which is a more secure way to get the user registration details. The above code also includes the form validation in PHP which is verifying the user details. mysqli_query(DB connection, query); is a MySQL function that performs a query against a database.

Parameter Values – mysqli_query(connection, query )

ParametersDescription
DB connectionRequired. Specifies the MySQL connection to use
queryRequired. Specifies the SQL query string
Details about mysqli_query() function’s parameters

password_hash() PHP function creates a new password hash using a strong one-way hashing algorithm. It uses a strong hashing algorithm. It adds a random salt to prevent rainbow tables and dictionary attacks.

$_session is a way to store user data (in variables) to be used across multiple pages on the website. The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers. A cookie is often used to identify a user.

User Logout PHP Code

The below code is used to log out with a session in PHP and log out PHP session.

//PHP code to logout user from website

  if (isset($_GET["logout"])) {
  	unset($_SESSION['id']);
    setcookie("id", "", time() - 3600);
    $_COOKIE['id'] = "";
  } 

The above PHP code is also part of the server.php file as said earlier. To log the user out from the website you need to use the unset() PHP function to unset the $_SESSION variable. In fact, we set the cookie to the past time and set the $_COOKIE[‘id’] to an empty string.

Final Words

In the above discussion, we have created the registration and login form in PHP and MySQL databases. If you want to implement the above user registration form in PHP on your website then you need to follow the procedures explained in this tutorial. If you still find any difficulty in understanding, feel free to contact this website www.hmawebdesign.com. If you found this tutorial helpful please don’t forget to SUBSCRIBE YOUTUBE CHANNEL.

Hit The Subscribe Button to Get Daily New video!

Spread the love, Share this Article!

Important Tags:

8 Responses

  1. F*ckin’ remarkаble things here. I am very gglad to see your post.
    Thank you a lot and i am looking aһead to contact you.
    Will you please dfop me a e-mail?

  2. It’s a pity you don’t have a donate button! I’d definitely donate to this
    outstanding blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account.
    I look forward to fresh updates and will talk about this website with
    my Facebook group. Talk soon!

  3. Thanks, I’ve just been looking for info approximately this topic for ages and yours is the greatest I’ve discovered so far. However, what concerning the conclusion? Are you certain in regards to the supply?

  4. Magnificent web site. Lots of helpful information here.

    I’m sending it to some pals ans also sharing in delicious.
    And of course, thanks on your sweat!

  5. Gooⅾ web site you’ve got here.. It’s difficult to find high quality writing like
    yourѕ nowadays. I seriously appreciate people like you!
    Take care!!

  6. You could definitely see your skills within the article you write.

    The arena hopes for more passionate writers such as you who are not afraid to mention how they
    believe. At all times follow your heart.
    Try Before you Buy 2021

Leave a Reply

Your email address will not be published.