banner



How Php Form Register Page Add Users In Phpmyadmin?

PHP MySQL Login Organisation

In this tutorial yous will larn how to build a login system with PHP and MySQL.

Implementing User Authentication Mechanism

User hallmark is very common in modern web application. It is a security machinery that is used to restrict unauthorized admission to member-just areas and tools on a site.

In this tutorial we'll create a elementary registration and login system using the PHP and MySQL. This tutorial is comprised of two parts: in the commencement role we'll create a user registration class, and in the 2d part we'll create a login form, as well as a welcome page and a logout script.

Building the Registration System

In this department we'll build a registration arrangement that allows users to create a new business relationship by filling out a web form. Just, outset we need to create a tabular array that will hold all the user data.

Footstep 1: Creating the Database Table

Execute the following SQL query to create the users tabular array within your MySQL database.

            CREATE Table users (     id INT NOT NULL Master Cardinal AUTO_INCREMENT,     username VARCHAR(l) Non Nix UNIQUE,     countersign VARCHAR(255) Non Zilch,     created_at DATETIME DEFAULT CURRENT_TIMESTAMP );          

Please bank check out the tutorial on SQL CREATE TABLE statement for the detailed information near syntax for creating tables in MySQL database system.

Step 2: Creating the Config File

After creating the tabular array, nosotros need create a PHP script in social club to connect to the MySQL database server. Let's create a file named "config.php" and put the following code inside information technology.

Instance

Procedural Object Oriented PDO

Download

            <?php /* Database credentials. Bold y'all are running MySQL server with default setting (user 'root' with no countersign) */ ascertain('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'demo');   /* Attempt to connect to MySQL database */ $link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);   // Check connection if($link === false){     dice("ERROR: Could not connect. " . mysqli_connect_error()); } ?>          
            <?php /* Database credentials. Bold yous are running MySQL server with default setting (user 'root' with no password) */ ascertain('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'demo');   /* Attempt to connect to MySQL database */ $mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);   // Check connection if($mysqli === faux){     die("ERROR: Could not connect. " . $mysqli->connect_error); } ?>          
            <?php /* Database credentials. Bold you are running MySQL server with default setting (user 'root' with no password) */ define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'demo');   /* Try to connect to MySQL database */ endeavor{     $pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);     // Fix the PDO error mode to exception     $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e){     dice("Error: Could not connect. " . $east->getMessage()); } ?>          

If you've downloaded the Object Oriented or PDO lawmaking examples using the download button, please remove the text "-oo-format" or "-pdo-format" from file names before testing the code.

Note: Supervene upon the credentials according to your MySQL server setting before testing this code, for example, replace the database proper noun 'demo' with your own database name, replace username 'root' with your ain database username, specify database password if there's any.

Stride iii: Creating the Registration Course

Allow's create some other PHP file "register.php" and put the following example lawmaking in information technology. This example code volition create a web form that allows user to annals themselves.

This script will also generate errors if a user tries to submit the form without entering any value, or if username entered by the user is already taken by another user.

Example

Procedural Object Oriented PDO

Download

            <?php // Include config file require_once "config.php";   // Define variables and initialize with empty values $username = $password = $confirm_password = ""; $username_err = $password_err = $confirm_password_err = "";   // Processing form data when course is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){       // Validate username     if(empty(trim($_POST["username"]))){         $username_err = "Please enter a username.";     } elseif(!preg_match('/^[a-zA-Z0-9_]+$/', trim($_POST["username"]))){         $username_err = "Username can but incorporate letters, numbers, and underscores.";     } else{         // Ready a select argument         $sql = "SELECT id FROM users WHERE username = ?";                  if($stmt = mysqli_prepare($link, $sql)){             // Bind variables to the prepared statement as parameters             mysqli_stmt_bind_param($stmt, "s", $param_username);                          // Prepare parameters             $param_username = trim($_POST["username"]);                          // Attempt to execute the prepared statement             if(mysqli_stmt_execute($stmt)){                 /* shop result */                 mysqli_stmt_store_result($stmt);                                  if(mysqli_stmt_num_rows($stmt) == 1){                     $username_err = "This username is already taken.";                 } else{                     $username = trim($_POST["username"]);                 }             } else{                 echo "Oops! Something went wrong. Please try again later.";             }              // Close statement             mysqli_stmt_close($stmt);         }     }          // Validate password     if(empty(trim($_POST["password"]))){         $password_err = "Please enter a password.";          } elseif(strlen(trim($_POST["password"])) < half-dozen){         $password_err = "Password must have atleast half dozen characters.";     } else{         $password = trim($_POST["password"]);     }          // Validate confirm password     if(empty(trim($_POST["confirm_password"]))){         $confirm_password_err = "Please ostend password.";          } else{         $confirm_password = trim($_POST["confirm_password"]);         if(empty($password_err) && ($countersign != $confirm_password)){             $confirm_password_err = "Password did non match.";         }     }          // Bank check input errors before inserting in database     if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){                  // Gear up an insert statement         $sql = "INSERT INTO users (username, password) VALUES (?, ?)";                   if($stmt = mysqli_prepare($link, $sql)){             // Bind variables to the prepared argument as parameters             mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);                          // Gear up parameters             $param_username = $username;             $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a countersign hash                          // Endeavor to execute the prepared argument             if(mysqli_stmt_execute($stmt)){                 // Redirect to login page                 header("location: login.php");             } else{                 echo "Oops! Something went wrong. Delight try once again later.";             }              // Close argument             mysqli_stmt_close($stmt);         }     }          // Close connection     mysqli_close($link); } ?>   <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Sign Up</championship>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.five.2/css/bootstrap.min.css">     <style>         body{ font: 14px sans-serif; }         .wrapper{ width: 360px; padding: 20px; }     </manner> </head> <body>     <div class="wrapper">         <h2>Sign Upwards</h2>         <p>Please fill this class to create an account.</p>         <form activity="<?php repeat htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">             <div class="form-group">                 <characterization>Username</characterization>                 <input type="text" name="username" class="class-command <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">                 <span class="invalid-feedback"><?php echo $username_err; ?></span>             </div>                 <div form="form-group">                 <label>Countersign</label>                 <input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $password; ?>">                 <bridge class="invalid-feedback"><?php repeat $password_err; ?></span>             </div>             <div grade="class-group">                 <characterization>Confirm Password</characterization>                 <input blazon="password" name="confirm_password" class="form-control <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $confirm_password; ?>">                 <span form="invalid-feedback"><?php echo $confirm_password_err; ?></bridge>             </div>             <div form="form-group">                 <input type="submit" class="btn btn-master" value="Submit">                 <input type="reset" form="btn btn-secondary ml-2" value="Reset">             </div>             <p>Already have an account? <a href="login.php">Login here</a>.</p>         </form>     </div>     </trunk> </html>          
            <?php // Include config file require_once "config.php";   // Ascertain variables and initialize with empty values $username = $password = $confirm_password = ""; $username_err = $password_err = $confirm_password_err = "";   // Processing grade data when grade is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){       // Validate username     if(empty(trim($_POST["username"]))){         $username_err = "Please enter a username.";     } elseif(!preg_match('/^[a-zA-Z0-9_]+$/', trim($_POST["username"]))){         $username_err = "Username tin simply comprise letters, numbers, and underscores.";     } else{         // Fix a select argument         $sql = "SELECT id FROM users WHERE username = ?";                  if($stmt = $mysqli->prepare($sql)){             // Bind variables to the prepared statement every bit parameters             $stmt->bind_param("south", $param_username);                          // Set parameters             $param_username = trim($_POST["username"]);                          // Attempt to execute the prepared statement             if($stmt->execute()){                 // store result                 $stmt->store_result();                                  if($stmt->num_rows == ane){                     $username_err = "This username is already taken.";                 } else{                     $username = trim($_POST["username"]);                 }             } else{                 echo "Oops! Something went wrong. Please try once more later.";             }              // Close argument             $stmt->close();         }     }          // Validate password     if(empty(trim($_POST["countersign"]))){         $password_err = "Please enter a password.";          } elseif(strlen(trim($_POST["countersign"])) < half dozen){         $password_err = "Password must have atleast half dozen characters.";     } else{         $password = trim($_POST["password"]);     }          // Validate confirm password     if(empty(trim($_POST["confirm_password"]))){         $confirm_password_err = "Please ostend password.";          } else{         $confirm_password = trim($_POST["confirm_password"]);         if(empty($password_err) && ($password != $confirm_password)){             $confirm_password_err = "Password did not match.";         }     }          // Check input errors before inserting in database     if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){                  // Prepare an insert statement         $sql = "INSERT INTO users (username, countersign) VALUES (?, ?)";                   if($stmt = $mysqli->gear up($sql)){             // Bind variables to the prepared statement as parameters             $stmt->bind_param("ss", $param_username, $param_password);                          // Prepare parameters             $param_username = $username;             $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash                          // Attempt to execute the prepared statement             if($stmt->execute()){                 // Redirect to login page                 header("location: login.php");             } else{                 echo "Oops! Something went wrong. Please try over again afterwards.";             }              // Close statement             $stmt->shut();         }     }          // Close connection     $mysqli->close(); } ?>   <!DOCTYPE html> <html lang="en"> <caput>     <meta charset="UTF-8">     <championship>Sign Up</title>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/iv.five.2/css/bootstrap.min.css">     <style>         body{ font: 14px sans-serif; }         .wrapper{ width: 360px; padding: 20px; }     </style> </caput> <torso>     <div class="wrapper">         <h2>Sign Upwards</h2>         <p>Please fill this form to create an account.</p>         <form activity="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="mail service">             <div grade="form-grouping">                 <label>Username</label>                 <input type="text" name="username" form="form-command <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">                 <span class="invalid-feedback"><?php repeat $username_err; ?></bridge>             </div>                 <div class="form-group">                 <characterization>Countersign</label>                 <input type="countersign" name="password" class="form-command <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $countersign; ?>">                 <bridge form="invalid-feedback"><?php repeat $password_err; ?></bridge>             </div>             <div class="grade-group">                 <label>Confirm Password</label>                 <input type="password" name="confirm_password" class="class-command <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>" value="<?php repeat $confirm_password; ?>">                 <span course="invalid-feedback"><?php echo $confirm_password_err; ?></span>             </div>             <div form="form-group">                 <input type="submit" class="btn btn-primary" value="Submit">                 <input blazon="reset" class="btn btn-secondary ml-2" value="Reset">             </div>             <p>Already have an account? <a href="login.php">Login hither</a>.</p>         </form>     </div>     </body> </html>          
            <?php // Include config file require_once "config.php";   // Define variables and initialize with empty values $username = $password = $confirm_password = ""; $username_err = $password_err = $confirm_password_err = "";   // Processing form data when grade is submitted if($_SERVER["REQUEST_METHOD"] == "Mail"){       // Validate username     if(empty(trim($_POST["username"]))){         $username_err = "Please enter a username.";     } elseif(!preg_match('/^[a-zA-Z0-9_]+$/', trim($_POST["username"]))){         $username_err = "Username can merely contain letters, numbers, and underscores.";     } else{         // Set a select statement         $sql = "SELECT id FROM users WHERE username = :username";                  if($stmt = $pdo->gear up($sql)){             // Bind variables to the prepared statement equally parameters             $stmt->bindParam(":username", $param_username, PDO::PARAM_STR);                          // Set up parameters             $param_username = trim($_POST["username"]);                          // Attempt to execute the prepared statement             if($stmt->execute()){                 if($stmt->rowCount() == 1){                     $username_err = "This username is already taken.";                 } else{                     $username = trim($_POST["username"]);                 }             } else{                 echo "Oops! Something went wrong. Please try again later on.";             }              // Close statement             unset($stmt);         }     }          // Validate password     if(empty(trim($_POST["countersign"]))){         $password_err = "Please enter a password.";          } elseif(strlen(trim($_POST["password"])) < 6){         $password_err = "Countersign must have atleast 6 characters.";     } else{         $password = trim($_POST["password"]);     }          // Validate ostend password     if(empty(trim($_POST["confirm_password"]))){         $confirm_password_err = "Please confirm password.";          } else{         $confirm_password = trim($_POST["confirm_password"]);         if(empty($password_err) && ($countersign != $confirm_password)){             $confirm_password_err = "Password did not match.";         }     }          // Bank check input errors before inserting in database     if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){                  // Set an insert statement         $sql = "INSERT INTO users (username, password) VALUES (:username, :password)";                   if($stmt = $pdo->prepare($sql)){             // Bind variables to the prepared statement every bit parameters             $stmt->bindParam(":username", $param_username, PDO::PARAM_STR);             $stmt->bindParam(":password", $param_password, PDO::PARAM_STR);                          // Fix parameters             $param_username = $username;             $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a countersign hash                          // Attempt to execute the prepared statement             if($stmt->execute()){                 // Redirect to login page                 header("location: login.php");             } else{                 echo "Oops! Something went wrong. Please endeavor once more afterward.";             }              // Shut statement             unset($stmt);         }     }          // Close connectedness     unset($pdo); } ?>   <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <championship>Sign Upward</title>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/iv.5.two/css/bootstrap.min.css">     <manner>         body{ font: 14px sans-serif; }         .wrapper{ width: 360px; padding: 20px; }     </style> </head> <body>     <div class="wrapper">         <h2>Sign Upwards</h2>         <p>Delight fill this form to create an account.</p>         <class activity="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="postal service">             <div grade="form-grouping">                 <characterization>Username</label>                 <input type="text" name="username" class="class-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">                 <span class="invalid-feedback"><?php echo $username_err; ?></span>             </div>                 <div class="class-group">                 <characterization>Password</label>                 <input type="countersign" name="countersign" grade="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>" value="<?php repeat $password; ?>">                 <span class="invalid-feedback"><?php repeat $password_err; ?></span>             </div>             <div class="form-group">                 <label>Ostend Password</label>                 <input type="password" name="confirm_password" class="form-control <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $confirm_password; ?>">                 <span class="invalid-feedback"><?php echo $confirm_password_err; ?></span>             </div>             <div class="form-group">                 <input type="submit" class="btn btn-primary" value="Submit">                 <input blazon="reset" class="btn btn-secondary ml-2" value="Reset">             </div>             <p>Already take an account? <a href="login.php">Login here</a>.</p>         </form>     </div>     </body> </html>          

— The output of the above example (i.e. signup form) will await something like this:

PHP MySQL Sign Up Form

In the above instance, we have used the PHP's inbuilt password_hash() function to create a password hash from the password cord entered by the user (line no-78). This role creates a countersign hash using a stiff one-way hashing algorithm. It likewise generates and applies a random salt automatically when hashing the password; this basically means that even if 2 users have the same passwords, their countersign hashes volition be unlike.

At the fourth dimension of login nosotros'll verify the given countersign with the password hash stored in the database using the PHP password_verify() function, every bit demonstrated in the next example.

We've used the Bootstrap framework to make the form layouts speedily and beautifully. Delight, checkout the Bootstrap tutorial section to learn more nearly this framework.

Tip: Password salting is a technique which is widely used to secure passwords by randomizing password hashes, so that if two users have the same password, they volition non have the same password hashes. This is done by appending or prepending a random string, chosen a salt, to the countersign before hashing.


Building the Login System

In this department we'll create a login form where user can enter their username and countersign. When user submit the class these inputs will exist verified against the credentials stored in the database, if the username and password match, the user is authorized and granted access to the site, otherwise the login effort will exist rejected.

Step 1: Creating the Login Course

Let's create a file named "login.php" and place the following lawmaking inside information technology.

Example

Procedural Object Oriented PDO

Download

            <?php // Initialize the session session_start();   // Check if the user is already logged in, if yes then redirect him to welcome page if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){     header("location: welcome.php");     exit; }   // Include config file require_once "config.php";   // Define variables and initialize with empty values $username = $countersign = ""; $username_err = $password_err = $login_err = "";   // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){       // Check if username is empty     if(empty(trim($_POST["username"]))){         $username_err = "Please enter username.";     } else{         $username = trim($_POST["username"]);     }          // Check if countersign is empty     if(empty(trim($_POST["password"]))){         $password_err = "Please enter your countersign.";     } else{         $password = trim($_POST["password"]);     }          // Validate credentials     if(empty($username_err) && empty($password_err)){         // Prepare a select statement         $sql = "SELECT id, username, countersign FROM users WHERE username = ?";                  if($stmt = mysqli_prepare($link, $sql)){             // Bind variables to the prepared statement equally parameters             mysqli_stmt_bind_param($stmt, "due south", $param_username);                          // Gear up parameters             $param_username = $username;                          // Attempt to execute the prepared argument             if(mysqli_stmt_execute($stmt)){                 // Shop result                 mysqli_stmt_store_result($stmt);                                  // Check if username exists, if yes then verify password                 if(mysqli_stmt_num_rows($stmt) == 1){                                         // Bind result variables                     mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);                     if(mysqli_stmt_fetch($stmt)){                         if(password_verify($countersign, $hashed_password)){                             // Password is correct, so offset a new session                             session_start();                                                          // Store information in session variables                             $_SESSION["loggedin"] = truthful;                             $_SESSION["id"] = $id;                             $_SESSION["username"] = $username;                                                                                      // Redirect user to welcome page                             header("location: welcome.php");                         } else{                             // Password is not valid, display a generic error message                             $login_err = "Invalid username or password.";                         }                     }                 } else{                     // Username doesn't exist, display a generic error message                     $login_err = "Invalid username or password.";                 }             } else{                 echo "Oops! Something went wrong. Please attempt again later.";             }              // Close argument             mysqli_stmt_close($stmt);         }     }          // Close connection     mysqli_close($link); } ?>   <!DOCTYPE html> <html lang="en"> <caput>     <meta charset="UTF-8">     <title>Login</championship>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/four.5.2/css/bootstrap.min.css">     <fashion>         body{ font: 14px sans-serif; }         .wrapper{ width: 360px; padding: 20px; }     </style> </head> <body>     <div course="wrapper">         <h2>Login</h2>         <p>Please fill up in your credentials to login.</p>          <?php          if(!empty($login_err)){             echo '<div grade="alert alert-danger">' . $login_err . '</div>';         }                 ?>          <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">             <div form="form-grouping">                 <label>Username</characterization>                 <input blazon="text" name="username" course="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">                 <bridge class="invalid-feedback"><?php repeat $username_err; ?></span>             </div>                 <div class="grade-grouping">                 <label>Countersign</label>                 <input blazon="password" name="countersign" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">                 <span form="invalid-feedback"><?php repeat $password_err; ?></span>             </div>             <div form="form-group">                 <input blazon="submit" course="btn btn-principal" value="Login">             </div>             <p>Don't have an account? <a href="register.php">Sign upwardly now</a>.</p>         </form>     </div> </torso> </html>          
            <?php // Initialize the session session_start();   // Check if the user is already logged in, if yes and then redirect him to welcome page if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){     header("location: welcome.php");     go out; }   // Include config file require_once "config.php";   // Define variables and initialize with empty values $username = $password = ""; $username_err = $password_err = $login_err = "";   // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "Mail"){       // Check if username is empty     if(empty(trim($_POST["username"]))){         $username_err = "Delight enter username.";     } else{         $username = trim($_POST["username"]);     }          // Check if password is empty     if(empty(trim($_POST["password"]))){         $password_err = "Please enter your countersign.";     } else{         $password = trim($_POST["countersign"]);     }          // Validate credentials     if(empty($username_err) && empty($password_err)){         // Fix a select statement         $sql = "SELECT id, username, password FROM users WHERE username = ?";                  if($stmt = $mysqli->prepare($sql)){             // Demark variables to the prepared statement as parameters             $stmt->bind_param("s", $param_username);                          // Ready parameters             $param_username = $username;                          // Attempt to execute the prepared statement             if($stmt->execute()){                 // Store consequence                 $stmt->store_result();                                  // Bank check if username exists, if yep and so verify password                 if($stmt->num_rows == 1){                                         // Bind result variables                     $stmt->bind_result($id, $username, $hashed_password);                     if($stmt->fetch()){                         if(password_verify($password, $hashed_password)){                             // Password is correct, and so first a new session                             session_start();                                                          // Store data in session variables                             $_SESSION["loggedin"] = true;                             $_SESSION["id"] = $id;                             $_SESSION["username"] = $username;                                                                                      // Redirect user to welcome page                             header("location: welcome.php");                         } else{                             // Password is not valid, display a generic error bulletin                             $login_err = "Invalid username or password.";                         }                     }                 } else{                     // Username doesn't exist, display a generic mistake message                     $login_err = "Invalid username or password.";                 }             } else{                 echo "Oops! Something went wrong. Please try once more later.";             }              // Close statement             $stmt->close();         }     }          // Close connection     $mysqli->close(); } ?>   <!DOCTYPE html> <html lang="en"> <caput>     <meta charset="UTF-8">     <title>Login</title>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/four.5.2/css/bootstrap.min.css">     <manner>         trunk{ font: 14px sans-serif; }         .wrapper{ width: 360px; padding: 20px; }     </style> </caput> <body>     <div course="wrapper">         <h2>Login</h2>         <p>Please fill in your credentials to login.</p>          <?php          if(!empty($login_err)){             echo '<div form="alert alert-danger">' . $login_err . '</div>';         }                 ?>          <form action="<?php repeat htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">             <div grade="form-group">                 <label>Username</label>                 <input type="text" proper noun="username" class="course-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php repeat $username; ?>">                 <span class="invalid-feedback"><?php echo $username_err; ?></span>             </div>                 <div class="form-grouping">                 <label>Password</label>                 <input type="password" proper name="countersign" course="course-command <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">                 <span course="invalid-feedback"><?php echo $password_err; ?></span>             </div>             <div class="grade-group">                 <input type="submit" class="btn btn-primary" value="Login">             </div>             <p>Don't take an account? <a href="register.php">Sign up at present</a>.</p>         </class>     </div> </body> </html>          
            <?php // Initialize the session session_start();   // Check if the user is already logged in, if yes and then redirect him to welcome page if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === truthful){     header("location: welcome.php");     exit; }   // Include config file require_once "config.php";   // Ascertain variables and initialize with empty values $username = $password = ""; $username_err = $password_err = $login_err = "";   // Processing course information when course is submitted if($_SERVER["REQUEST_METHOD"] == "Mail service"){       // Bank check if username is empty     if(empty(trim($_POST["username"]))){         $username_err = "Please enter username.";     } else{         $username = trim($_POST["username"]);     }          // Bank check if password is empty     if(empty(trim($_POST["password"]))){         $password_err = "Please enter your password.";     } else{         $countersign = trim($_POST["password"]);     }          // Validate credentials     if(empty($username_err) && empty($password_err)){         // Prepare a select argument         $sql = "SELECT id, username, password FROM users WHERE username = :username";                  if($stmt = $pdo->prepare($sql)){             // Demark variables to the prepared statement every bit parameters             $stmt->bindParam(":username", $param_username, PDO::PARAM_STR);                          // Set up parameters             $param_username = trim($_POST["username"]);                          // Effort to execute the prepared statement             if($stmt->execute()){                 // Bank check if username exists, if yes then verify password                 if($stmt->rowCount() == 1){                     if($row = $stmt->fetch()){                         $id = $row["id"];                         $username = $row["username"];                         $hashed_password = $row["password"];                         if(password_verify($password, $hashed_password)){                             // Password is correct, and then start a new session                             session_start();                                                          // Store information in session variables                             $_SESSION["loggedin"] = true;                             $_SESSION["id"] = $id;                             $_SESSION["username"] = $username;                                                                                      // Redirect user to welcome page                             header("location: welcome.php");                         } else{                             // Password is not valid, brandish a generic error message                             $login_err = "Invalid username or password.";                         }                     }                 } else{                     // Username doesn't exist, brandish a generic fault message                     $login_err = "Invalid username or countersign.";                 }             } else{                 echo "Oops! Something went incorrect. Please attempt again afterward.";             }              // Shut argument             unset($stmt);         }     }          // Close connection     unset($pdo); } ?>   <!DOCTYPE html> <html lang="en"> <caput>     <meta charset="UTF-8">     <title>Login</title>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/four.5.ii/css/bootstrap.min.css">     <mode>         torso{ font: 14px sans-serif; }         .wrapper{ width: 360px; padding: 20px; }     </style> </caput> <trunk>     <div grade="wrapper">         <h2>Login</h2>         <p>Please make full in your credentials to login.</p>          <?php          if(!empty($login_err)){             echo '<div class="alert alert-danger">' . $login_err . '</div>';         }                 ?>          <course action="<?php repeat htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">             <div class="form-group">                 <label>Username</label>                 <input type="text" proper noun="username" class="form-control <?php repeat (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">                 <span class="invalid-feedback"><?php echo $username_err; ?></span>             </div>                 <div course="form-group">                 <label>Countersign</characterization>                 <input type="password" proper noun="countersign" class="form-command <?php repeat (!empty($password_err)) ? 'is-invalid' : ''; ?>">                 <span class="invalid-feedback"><?php repeat $password_err; ?></span>             </div>             <div form="form-group">                 <input blazon="submit" class="btn btn-primary" value="Login">             </div>             <p>Don't have an account? <a href="register.php">Sign up at present</a>.</p>         </course>     </div> </body> </html>          

— The output of the above instance (i.east. login form) will look something like this:

PHP MySQL Login Form

Pace two: Creating the Welcome Page

Here's the code of our "welcome.php" file, where user is redirected afterward successful login.

            <?php // Initialize the session session_start();   // Bank check if the user is logged in, if not then redirect him to login page if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){     header("location: login.php");     exit; } ?>   <!DOCTYPE html> <html lang="en"> <caput>     <meta charset="UTF-viii">     <championship>Welcome</title>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/four.v.2/css/bootstrap.min.css">     <mode>         torso{ font: 14px sans-serif; text-align: center; }     </fashion> </caput> <torso>     <h1 grade="my-5">Hi, <b><?php repeat htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>     <p>         <a href="reset-password.php" course="btn btn-warning">Reset Your Countersign</a>         <a href="logout.php" class="btn btn-danger ml-3">Sign Out of Your Business relationship</a>     </p> </body> </html>          

If data comes from external sources like course filled in past anonymous users, in that location is a adventure that information technology may incorporate malicious script indented to launch cross-site scripting (XSS) attacks. Therefore, you lot must escape this data using the PHP htmlspecialchars() function earlier displaying it in the browser, so that whatsoever HTML tag information technology contains becomes harmless.

For example, after escaping special characters the string <script>alert("XSS")</script> becomes &lt;script&gt;warning("XSS")&lt;/script&gt; which is non executed by the browser.

Pace 3: Creating the Logout Script

Now, let'due south create a "logout.php" file. When the user clicks on the log out or sign out link, the script inside this file destroys the session and redirect the user back to the login page.

            <?php // Initialize the session session_start();   // Unset all of the session variables $_SESSION = array();   // Destroy the session. session_destroy();   // Redirect to login folio header("location: login.php"); exit; ?>          

Adding the Countersign Reset Feature

Finally, in this department we will add the password reset utility to our login organisation. Using this feature logged in users tin can instantly reset their own password for their accounts.

Let'southward create a file named "reset-countersign.php" and place the following code inside it.

Example

Procedural Object Oriented PDO

Download

            <?php // Initialize the session session_start();   // Cheque if the user is logged in, otherwise redirect to login page if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== truthful){     header("location: login.php");     exit; }   // Include config file require_once "config.php";   // Ascertain variables and initialize with empty values $new_password = $confirm_password = ""; $new_password_err = $confirm_password_err = "";   // Processing form data when grade is submitted if($_SERVER["REQUEST_METHOD"] == "Post"){       // Validate new password     if(empty(trim($_POST["new_password"]))){         $new_password_err = "Delight enter the new countersign.";          } elseif(strlen(trim($_POST["new_password"])) < 6){         $new_password_err = "Countersign must have atleast half-dozen characters.";     } else{         $new_password = trim($_POST["new_password"]);     }          // Validate confirm password     if(empty(trim($_POST["confirm_password"]))){         $confirm_password_err = "Please confirm the password.";     } else{         $confirm_password = trim($_POST["confirm_password"]);         if(empty($new_password_err) && ($new_password != $confirm_password)){             $confirm_password_err = "Password did not match.";         }     }              // Bank check input errors before updating the database     if(empty($new_password_err) && empty($confirm_password_err)){         // Prepare an update statement         $sql = "UPDATE users Prepare password = ? WHERE id = ?";                  if($stmt = mysqli_prepare($link, $sql)){             // Bind variables to the prepared statement as parameters             mysqli_stmt_bind_param($stmt, "si", $param_password, $param_id);                          // Set parameters             $param_password = password_hash($new_password, PASSWORD_DEFAULT);             $param_id = $_SESSION["id"];                          // Effort to execute the prepared statement             if(mysqli_stmt_execute($stmt)){                 // Password updated successfully. Destroy the session, and redirect to login folio                 session_destroy();                 header("location: login.php");                 exit();             } else{                 repeat "Oops! Something went wrong. Please try again after.";             }              // Shut argument             mysqli_stmt_close($stmt);         }     }          // Close connection     mysqli_close($link); } ?>   <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-eight">     <title>Reset Countersign</title>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/iv.5.ii/css/bootstrap.min.css">     <fashion>         body{ font: 14px sans-serif; }         .wrapper{ width: 360px; padding: 20px; }     </manner> </caput> <body>     <div class="wrapper">         <h2>Reset Password</h2>         <p>Please fill up out this form to reset your password.</p>         <course action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">              <div class="form-group">                 <characterization>New Password</label>                 <input type="password" name="new_password" class="grade-control <?php echo (!empty($new_password_err)) ? 'is-invalid' : ''; ?>" value="<?php repeat $new_password; ?>">                 <bridge class="invalid-feedback"><?php repeat $new_password_err; ?></span>             </div>             <div class="form-group">                 <characterization>Confirm Password</characterization>                 <input type="password" name="confirm_password" class="form-command <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>">                 <span grade="invalid-feedback"><?php echo $confirm_password_err; ?></span>             </div>             <div class="form-grouping">                 <input type="submit" class="btn btn-master" value="Submit">                 <a class="btn btn-link ml-two" href="welcome.php">Abolish</a>             </div>         </form>     </div>     </torso> </html>          
            <?php // Initialize the session session_start();   // Cheque if the user is logged in, otherwise redirect to login page if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){     header("location: login.php");     exit; }   // Include config file require_once "config.php";   // Define variables and initialize with empty values $new_password = $confirm_password = ""; $new_password_err = $confirm_password_err = "";   // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){       // Validate new countersign     if(empty(trim($_POST["new_password"]))){         $new_password_err = "Please enter the new password.";          } elseif(strlen(trim($_POST["new_password"])) < six){         $new_password_err = "Password must take atleast half-dozen characters.";     } else{         $new_password = trim($_POST["new_password"]);     }          // Validate confirm password     if(empty(trim($_POST["confirm_password"]))){         $confirm_password_err = "Please confirm the password.";     } else{         $confirm_password = trim($_POST["confirm_password"]);         if(empty($new_password_err) && ($new_password != $confirm_password)){             $confirm_password_err = "Password did not match.";         }     }              // Check input errors before updating the database     if(empty($new_password_err) && empty($confirm_password_err)){         // Prepare an update argument         $sql = "UPDATE users Ready password = ? WHERE id = ?";                  if($stmt = $mysqli->prepare($sql)){             // Bind variables to the prepared statement equally parameters             $stmt->bind_param("si", $param_password, $param_id);                          // Set parameters             $param_password = password_hash($new_password, PASSWORD_DEFAULT);             $param_id = $_SESSION["id"];                          // Attempt to execute the prepared argument             if($stmt->execute()){                 // Password updated successfully. Destroy the session, and redirect to login page                 session_destroy();                 header("location: login.php");                 exit();             } else{                 echo "Oops! Something went incorrect. Please try over again after.";             }              // Close statement             $stmt->shut();         }     }          // Shut connection     $mysqli->shut(); } ?>   <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Reset Countersign</title>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">     <style>         body{ font: 14px sans-serif; }         .wrapper{ width: 360px; padding: 20px; }     </fashion> </head> <body>     <div form="wrapper">         <h2>Reset Countersign</h2>         <p>Please fill out this form to reset your password.</p>         <course activeness="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">              <div course="form-group">                 <characterization>New Countersign</label>                 <input type="password" name="new_password" class="form-command <?php echo (!empty($new_password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $new_password; ?>">                 <bridge class="invalid-feedback"><?php repeat $new_password_err; ?></span>             </div>             <div class="class-group">                 <label>Confirm Countersign</label>                 <input type="password" name="confirm_password" course="form-command <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>">                 <span class="invalid-feedback"><?php echo $confirm_password_err; ?></span>             </div>             <div class="form-grouping">                 <input blazon="submit" class="btn btn-main" value="Submit">                 <a grade="btn btn-link ml-2" href="welcome.php">Cancel</a>             </div>         </form>     </div>     </body> </html>          
            <?php // Initialize the session session_start();   // Check if the user is logged in, otherwise redirect to login page if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== truthful){     header("location: login.php");     exit; }   // Include config file require_once "config.php";   // Ascertain variables and initialize with empty values $new_password = $confirm_password = ""; $new_password_err = $confirm_password_err = "";   // Processing form information when class is submitted if($_SERVER["REQUEST_METHOD"] == "Mail"){       // Validate new countersign     if(empty(trim($_POST["new_password"]))){         $new_password_err = "Please enter the new password.";          } elseif(strlen(trim($_POST["new_password"])) < 6){         $new_password_err = "Password must have atleast half-dozen characters.";     } else{         $new_password = trim($_POST["new_password"]);     }          // Validate ostend password     if(empty(trim($_POST["confirm_password"]))){         $confirm_password_err = "Please confirm the password.";     } else{         $confirm_password = trim($_POST["confirm_password"]);         if(empty($new_password_err) && ($new_password != $confirm_password)){             $confirm_password_err = "Password did non match.";         }     }              // Cheque input errors before updating the database     if(empty($new_password_err) && empty($confirm_password_err)){         // Gear up an update statement         $sql = "UPDATE users Fix password = :password WHERE id = :id";                  if($stmt = $pdo->prepare($sql)){             // Demark variables to the prepared statement as parameters             $stmt->bindParam(":countersign", $param_password, PDO::PARAM_STR);             $stmt->bindParam(":id", $param_id, PDO::PARAM_INT);                          // Fix parameters             $param_password = password_hash($new_password, PASSWORD_DEFAULT);             $param_id = $_SESSION["id"];                          // Attempt to execute the prepared argument             if($stmt->execute()){                 // Password updated successfully. Destroy the session, and redirect to login page                 session_destroy();                 header("location: login.php");                 exit();             } else{                 repeat "Oops! Something went wrong. Delight effort again later.";             }              // Close argument             unset($stmt);         }     }          // Shut connection     unset($pdo); } ?>   <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-viii">     <championship>Reset Countersign</championship>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">     <style>         body{ font: 14px sans-serif; }         .wrapper{ width: 360px; padding: 20px; }     </style> </head> <body>     <div class="wrapper">         <h2>Reset Password</h2>         <p>Please fill out this grade to reset your countersign.</p>         <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">              <div course="grade-group">                 <label>New Password</label>                 <input type="countersign" proper name="new_password" class="form-control <?php echo (!empty($new_password_err)) ? 'is-invalid' : ''; ?>" value="<?php repeat $new_password; ?>">                 <bridge class="invalid-feedback"><?php repeat $new_password_err; ?></span>             </div>             <div class="grade-group">                 <label>Confirm Password</characterization>                 <input type="password" name="confirm_password" class="course-control <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>">                 <bridge class="invalid-feedback"><?php repeat $confirm_password_err; ?></span>             </div>             <div class="form-grouping">                 <input type="submit" form="btn btn-master" value="Submit">                 <a class="btn btn-link ml-2" href="welcome.php">Abolish</a>             </div>         </form>     </div>     </body> </html>          

How Php Form Register Page Add Users In Phpmyadmin?,

Source: https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php

Posted by: hisleoffet1962.blogspot.com

0 Response to "How Php Form Register Page Add Users In Phpmyadmin?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel