Web Programming TutorialsCreating And Processing A Web Form Using HTML 5 & PHP

Creating And Processing A Web Form Using HTML 5 & PHP

This blog includes the end-to-end procedure of creating and processing a web form using HTML5 and PHP. Our example in this tutorial includes a registration web form which every website includes for registration of new users of website. The parameters included for the registration form include:

1. Username
2. E-mail
3. Password

Pre-requisites:

The primary pre-requisites include understanding PHP with SQL connectivity. It is assumed that user has primary setup of PHP web application installed in their system. We are using HTML5 for achieving validations of the form.
The procedure of creating and processing a web form using HTML5 and PHP are mentioned below:

First step which is mandatory for managing the forms starts with creation of database. As our website will primarily accept all the users in registration module, we will be considering the database name as “users” and table name with the same.

The data dictionary of “users” table is displayed below:

users-table

The columns included in “users” table are id (Primary key), username, email and passwords.
The database connectivity with PHP web application is achieved through following script:

<?php

$db_host = "localhost";
$db_name = "users";
$db_user = "root";
$db_pass = "";

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

Now we will focus on the registration form creation.
The look and feel of the registration form and login form are visible below:

register

login-form

The code for creating the registration form is mentioned below:

<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Registration</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css"/>
    <link rel="stylesheet" href="assets/css/style.css" type="text/css"/>
</head>
<body>

<div class="container">

    <div id="login-form">
        <form method="post" autocomplete="off">

            <div class="col-md-12">

                <div class="form-group">
                    <h2 class="">Register for our Website</h2>
                </div>

                <div class="form-group">
                    <hr/>
                </div>

                <?php
                if (isset($errMSG)) {

                    ?>
                    <div class="form-group">
                        <div class="alert alert-<?php echo ($errTyp == "success") ? "success" : $errTyp; ?>">
                            <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
                        </div>
                    </div>
                    <?php
                }
                ?>

                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
                        <input type="text" name="uname" class="form-control" placeholder="Enter Username" required/>
                    </div>
                </div>

                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
                        <input type="email" name="email" class="form-control" placeholder="Enter Email" required/>
                    </div>
                </div>

                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
                        <input type="password" name="pass" class="form-control" placeholder="Enter Password"
                               required/>
                    </div>
                </div>

                <div class="checkbox">
                    <label><input type="checkbox" id="TOS" value="This"><a href="#">I agree with
                            terms of service</a></label>
                </div>

                <div class="form-group">
                    <button type="submit" class="btn    btn-block btn-primary" name="signup" id="reg">Register</button>
                </div>

                <div class="form-group">
                    <hr/>
                </div>

                <div class="form-group">
                    <a href="login.php" type="button" class="btn btn-block btn-success" name="btn-login">Login</a>
                </div>

            </div>

        </form>
    </div>

</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/js/tos.js"></script>

</body>
</html>

In the above code, we have included the validations in every form input which is in-built in HTML5 and have included some third-party files and libraries including “.css” files for styling the view part.

The following code is placed before using the view part which means .html file with sole reason of achieving connectivity with database. In this section, we start a session using PHP and initialize the database connectivity with the help of file “dbconnect.php”. After initializing the connectivity, the parameters of username, email and password which are passed through HTML form is inserted in the users table. The insert query is same SQL standard query of “INSERT”.

<?php
ob_start();
session_start(); 
@charset "utf-8";
/* CSS Document */

*{
    margin:0;
    padding:0;
}
#login-form {
    margin:5% auto;
    max-width:500px;
}
/* home page */



#wrapper{
    padding-top:50px;
}

if (isset($_SESSION['user']) != "") {
header("Location: index.php");
}
include_once 'dbconnect.php';

if (isset($_POST['signup'])) {

$uname = trim($_POST['uname']); // get posted data and remove whitespace
$email = trim($_POST['email']);
$upass = trim($_POST['pass']);

// hash password with SHA256;
$password = hash('sha256', $upass);

// check email exist or not
$stmt = $conn->prepare("SELECT email FROM users WHERE email=?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();

$count = $result->num_rows;

if ($count == 0) { // if email is not found add user

$stmts = $conn->prepare("INSERT INTO users(username,email,password) VALUES(?, ?, ?)");
$stmts->bind_param("sss", $uname, $email, $password);
$res = $stmts->execute();//get result
$stmts->close();

$user_id = mysqli_insert_id($conn);
if ($user_id > 0) {
$_SESSION['user'] = $user_id; // set session and redirect to index page
if (isset($_SESSION['user'])) {
print_r($_SESSION);
header("Location: index.php");
exit;
}

} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again";
}

} else {
$errTyp = "warning";
$errMSG = "Email is already used";
}

}
?>

The styling of files are designed in two files namely: style.css and various plugins. The code snippet included in assets/style.css is mentioned below:

Once user the required parameters in registration form with proper validation check, we can click on the submit button and have a look on the records been inserted in the SQL database.

Registration-image

The successful insertion of input entries through form in database table is mentioned below:

users-entry

It is observed that the passwords are stored in SHA-1 hash format to maintain security. This security feature will not allow intruders to access passwords easily. In login form design, these passwords are decrypted and verified with user entry. If the user entry matches with password, the user can access the website else if authentication fails, the proper validation message is displayed.

The login form of website is designed as below:

<?php
ob_start();
session_start();
require_once 'dbconnect.php';

// if session is set direct to index
if (isset($_SESSION['user'])) {
    header("Location: index.php");
    exit;
}

if (isset($_POST['btn-login'])) {
    $email = $_POST['email'];
    $upass = $_POST['pass'];

    $password = hash('sha256', $upass); // password hashing using SHA256
    $stmt = $conn->prepare("SELECT id, username, password FROM users WHERE email= ?");
    $stmt->bind_param("s", $email);
    /* execute query */
    $stmt->execute();
    //get result
    $res = $stmt->get_result();
    $stmt->close();

    $row = mysqli_fetch_array($res, MYSQLI_ASSOC);

    $count = $res->num_rows;
    if ($count == 1 && $row['password'] == $password) {
        $_SESSION['user'] = $row['id'];
        header("Location: index.php");
    } elseif ($count == 1) {
        $errMSG = "Bad password";
    } else $errMSG = "User not found";
}
?>

<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Login</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css"/>
    <link rel="stylesheet" href="assets/css/style.css" type="text/css"/>
</head>
<body>

<div class="container">

    <div id="login-form">
        <form method="post" autocomplete="off">

            <div class="col-md-12">

                <div class="form-group">
                    <h2 class="">Login:</h2>
                </div>

                <div class="form-group">
                    <hr/>
                </div>

                <?php
                if (isset($errMSG)) {

                    ?>
                    <div class="form-group">
                        <div class="alert alert-danger">
                            <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
                        </div>
                    </div>
                    <?php
                }
                ?>

                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
                        <input type="email" name="email" class="form-control" placeholder="Email" required/>
                    </div>
                </div>

                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
                        <input type="password" name="pass" class="form-control" placeholder="Password" required/>
                    </div>
                </div>

                <div class="form-group">
                    <hr/>
                </div>

                <div class="form-group">
                    <button type="submit" class="btn btn-block btn-primary" name="btn-login">Login</button>
                </div>

                <div class="form-group">
                    <hr/>
                </div>

                <div class="form-group">
                    <a href="register.php" type="button" class="btn btn-block btn-danger"
                       name="btn-login">Register</a>
                </div>

            </div>

        </form>
    </div>

</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
</body>
</html>

The access of login form with username and password is demonstrated below:

login-form

The user dashboard after successful login is displayed below:

Hello demo eduonix com

The password matches with username inserted in the records of database table, the user has access to home page. If incorrect password is inserted, wrong validation message is shown up which says, “Bad password”.

login-fail

Conclusion:

In this tutorial, we have demonstrated creating a PHP contact form using AJAX, jQuery and MySQL. The primary focus is to include HTML5 tags for perfect view design along with database structure and queries inserted. Always keep a look on the action used which can be “Get” or “Post” method. As passwords are inserted, the recommended action to be used is “Post” method to maintain security.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -