How to Create Login And Register System in PHP MySQL
Hi Guys this article we are discuss about How to Create Login And Register System in PHP MySQL . if you are a senior web developer you must have created plenty of Login and Register system already. They maybe exist in a content management system, and inventory management system OR accounting application. if you just started web development, you are certainly going to experience lots Login and Register creation work in your later career.
How to Create Login And Register System in PHP MySQL
1-Creating Database
- Open Phpmyadmin in your Browser
- Click on Database Tab Display on Top side
- Give the Database name “login”.
- After Creating Database Open it.
- Click on SQL Tab on Top area
- Copy the Below Source Code and paste it.
- Then Click on Go.
-- phpMyAdmin SQL Dump -- version 4.7.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jan 21, 2018 at 08:58 PM -- Server version: 10.1.26-MariaDB -- PHP Version: 7.1.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `login` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(10) NOT NULL, `username` varchar(100) NOT NULL, `password` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `password`) VALUES (1, 'deepak', '123'), (2, 'admin', '$2y$10$8c0X//oA5Z0PhkJP1SKlcethYvGIstYd4YiMXUu/Vt92BoHWEunKG'), (3, 'testing', '$2y$10$G.Yj1r5WIyAQ1wcC0zfmLObN9TtNyUhzAY4utODFV17qWbh2aK7EK'), (4, 'admin123', '$2y$10$rOqZQ3ZHtjzSMy5twcGgEOijRSvll9hghuQ4on758MEEZPq2RnX1i'); -- -- Indexes for dumped tables -- -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
OR Import DB File
After Downloading the source code extract it in your root folder.
- Open Phpmyadmin in your Browser
- Click on Database Tab Display on Top side
- Give the Database name “login”.
- After Creating Database Open it.
- Click on Import Tab on Top area
- You can Find Db file in Downloaded source code Select it.
- Then Click on Go.
2- Creating Database Connection
After import Database File then next step is creating database connection using php copy the below code and save it is as “config.php”.
<?php /* Database credentials. Assuming 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', 'login'); /* Attempt to connect to MySQL database */ try{ $pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD); // Set the PDO error mode to exception $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e){ die("ERROR: Could not connect. " . $e->getMessage()); } ?>
3 – Creating Register Form and Sending Data Into MySQL
This step we are going to creating register form using simple html and validate form in php . save this code named register.php source code given below.
<?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 form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Validate username if(empty(trim($_POST["username"]))){ $username_err = "Please enter a username."; } else{ // Prepare a select statement $sql = "SELECT id FROM users WHERE username = :username"; if($stmt = $pdo->prepare($sql)){ // Bind variables to the prepared statement as parameters $stmt->bindParam(':username', $param_username, PDO::PARAM_STR); // Set 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."; } } // Close statement unset($stmt); } // Validate password if(empty(trim($_POST['password']))){ $password_err = "Please enter a password."; } elseif(strlen(trim($_POST['password'])) < 6){ $password_err = "Password must have atleast 6 characters."; } else{ $password = trim($_POST['password']); } // Validate confirm password if(empty(trim($_POST["confirm_password"]))){ $confirm_password_err = 'Please confirm password.'; } else{ $confirm_password = trim($_POST['confirm_password']); if($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, password) VALUES (:username, :password)"; if($stmt = $pdo->prepare($sql)){ // Bind variables to the prepared statement as parameters $stmt->bindParam(':username', $param_username, PDO::PARAM_STR); $stmt->bindParam(':password', $param_password, PDO::PARAM_STR); // Set 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: index.php"); } else{ echo "Something went wrong. Please try again later."; } } // Close statement unset($stmt); } // Close connection unset($pdo); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>How to Create Login And Register System in PHP MySQL</title> <meta name="description" content=""> <meta name="author" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/skeleton.css"> </head> <body> <div class="container"> <div class="container" style="border:1px solid gray; padding:15px; margin:15px; border-radius:10px;"> <br> <br> <h2>Sign Up</h2> <p>Please fill this form to create an account.</p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>"> <label>Username:<sup>*</sup></label> <input type="text" name="username"class="u-full-width" value="<?php echo $username; ?>"> <p><?php echo $username_err; ?></p> </div> <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>"> <label>Password:<sup>*</sup></label> <input type="password" name="password" class="u-full-width" value="<?php echo $password; ?>"> <p><?php echo $password_err; ?></p> </div> <div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>"> <label>Confirm Password:<sup>*</sup></label> <input type="password" name="confirm_password" class="u-full-width" value="<?php echo $confirm_password; ?>"> <p><?php echo $confirm_password_err; ?></p> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Submit"> <input type="reset" class="btn btn-default" value="Reset"> </div> <p>Already have an account? <a href="index.php">Login here</a>.</p> </form> </div> </div> </body> </html>
4 – Creating Login Form and Validate data using PHP MySQL
This step we are going to create login form and validate data server side using PHP MySQL. save this code named index.php source code given below.
<?php // Include config file require_once 'config.php'; // Define variables and initialize with empty values $username = $password = ""; $username_err = $password_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 password is empty if(empty(trim($_POST['password']))){ $password_err = 'Please enter your password.'; } else{ $password = trim($_POST['password']); } // Validate credentials if(empty($username_err) && empty($password_err)){ // Prepare a select statement $sql = "SELECT username, password FROM users WHERE username = :username"; if($stmt = $pdo->prepare($sql)){ // Bind variables to the prepared statement as parameters $stmt->bindParam(':username', $param_username, PDO::PARAM_STR); // Set parameters $param_username = trim($_POST["username"]); // Attempt to execute the prepared statement if($stmt->execute()){ // Check if username exists, if yes then verify password if($stmt->rowCount() == 1){ if($row = $stmt->fetch()){ $hashed_password = $row['password']; if(password_verify($password, $hashed_password)){ /* Password is correct, so start a new session and save the username to the session */ session_start(); $_SESSION['username'] = $username; header("location: welcome.php"); } else{ // Display an error message if password is not valid $password_err = 'The password you entered was not valid.'; } } } else{ // Display an error message if username doesn't exist $username_err = 'No account found with that username.'; } } else{ echo "Oops! Something went wrong. Please try again later."; } } // Close statement unset($stmt); } // Close connection unset($pdo); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>How to Create Login And Register System in PHP MySQL</title> <meta name="description" content=""> <meta name="author" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/skeleton.css"> </head> <body> <div class="container"> <div class="container" style="border:1px solid gray; padding:15px; margin:15px; border-radius:10px;"> <br><br> <h2>Login</h2> <p>Please fill in your credentials to login.</p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>"> <label>Username:<sup>*</sup></label> <input type="text" name="username"class="u-full-width" value="<?php echo $username; ?>"> <p><?php echo $username_err; ?></p> </div> <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>"> <label>Password:<sup>*</sup></label> <input type="password" name="password" class="u-full-width"> <p><?php echo $password_err; ?></p> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Submit"> </div> <p>Don't have an account? <a href="register.php">Sign up here</a>.</p> </form> </div> </div> </body> </html>
5 – Creating Welcome Page Showing after Login
This step we create a page named welcome.php . when user login then see this page after login. Source code are given below.
<?php // Initialize the session session_start(); // If session variable is not set it will redirect to login page if(!isset($_SESSION['username']) || empty($_SESSION['username'])){ header("location: login.php"); exit; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>How to Create Login And Register System in PHP MySQL</title> <meta name="description" content=""> <meta name="author" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/skeleton.css"> <link rel="icon" type="image/png" href="images/favicon.png"> </head> <body> <div class="container"> <div class="container" style="border:1px solid gray; padding:15px; margin:15px; border-radius:10px; width:100%;"> <br> <br> <h1>Hi, <b><?php echo $_SESSION['username']; ?></b>. Welcome to Dashboard.</h1> <img src="images/dash.png"> <p><a href="logout.php" class="button">Sign Out of Your Account</a></p> </div> </div> </body> </html>
If you facing any type of problem with this source code then you can Download the Complete source code in zip Formate by clicking the below button Download Now otherwise you can send Comment.