Ad Code

Ticker

6/recent/ticker-posts

PHP login and registration script with mysql example


For the login system firstly create a database of the following script and table design inside MySQL. There are only login and registration systems then we can create only one table name is users, which has column id, name, email, password, created_at, and updated_at, etc.

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
here created_at for the DateTime store for registration time and updated_at store timestamp when use updates any column. The email column should unique because email id as login id and it must be unique.

Create DB config.php:-
In this file store database configuration is used everywhere required database config like host, username, password, and DB name.
<?php

$DB_HOST = "localhost"; //you can replace your db host
$DB_USER = "root"; // you can replace your db user
$DB_PASS = "root"; // you can replace your db password
$DB_NAME = "mydb"; // you can replace your db name

// Create connection
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

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

?>

After that create login and registration form in HTML using bootstrap, because bootstrap provides a large CSS class which uses to create very easily web designing.

Registration:-
Inside registration form be will use only 4 inputs, one submit button, and one link to go the login page.
and inside registration form set the condition when form post-run inside PHP script if not then run the HTML part. here we are using the same page for HTML and back-end script PHP for performing DB operations for validation using javascript to alert messages.
<?php
if(!empty($_POST)){
	require_once( 'config.php' );
	if(empty($_POST['name'])){
		echo "<script>alert('Name is required.');window.location.href='registration.php';</script>";
	}
	if(empty($_POST['email'])){
		echo "<script>alert('Email is required.');window.location.href='registration.php';</script>";
	}
	if(empty($_POST['password'])){
		echo "<script>alert('Password is required.');window.location.href='registration.php';</script>";
	}
	if(empty($_POST['cpassword'])){
		echo "<script>alert('Confirm password is required.');window.location.href='registration.php';</script>";
	}
	if($_POST['password'] != $_POST['cpassword']){
		echo "<script>alert('Password and confirm password does not match.');window.location.href='registration.php';</script>";
	}
	
	$sql = "INSERT INTO users (name, email, password) VALUES ('".$_POST['name']."', '".$_POST['email']."', '".$_POST['password']."')";

	if ($conn->query($sql) === TRUE) {
	  echo "<script>alert('New record created successfully, Enter email id and password for login.');window.location.href='index.php';</script>";
	} else {
	  //echo "Error: " . $sql . "<br>" . $conn->error;
	  echo "<script>alert('$conn->error');window.location.href='registration.php';</script>";
	}
	
	$conn->close();
	
}else{
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Registration</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
	  <h2>Registration form</h2>
	  <form action="?" method="POST">
		<div class="form-group">
		  <label for="name">Name:</label>
		  <input type="text" class="form-control" id="name" placeholder="Enter name" name="name">
		</div>
		<div class="form-group">
		  <label for="email">Email:</label>
		  <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
		</div>
		<div class="form-group">
		  <label for="pwd">Password:</label>
		  <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="password">
		</div>
		<div class="form-group">
		  <label for="pwd">Confirm-Password:</label>
		  <input type="password" class="form-control" id="cpwd" placeholder="Enter confirm password" name="cpassword">
		</div>
		<button type="submit" class="btn btn-primary">Submit</button>
		<br>
		<br>
		<a href="index.php">Login</a>
	  </form>
	</div>
</body>
</html>

<?php } ?>
Login:-
In the login form use email and password as for login credentials. 
<?php
session_start();
if(!empty($_SESSION["login"])){
	echo "<script>window.location.href='home.php';</script>";
}
if(!empty($_POST)){
	require_once( 'config.php' );
	if(empty($_POST['email'])){
		echo "<script>alert('Email is required.');window.location.href='registration.php';</script>";
	}
	if(empty($_POST['password'])){
		echo "<script>alert('Password is required.');window.location.href='registration.php';</script>";
	}
	
	$sql = "SELECT id, name, email FROM users WHERE email='".$_POST['email']."' AND password='".$_POST['password']."'";
	$result = $conn->query($sql);

	if ($result->num_rows > 0) {
	  // output data of each row
	  while($row = $result->fetch_assoc()) {
		//echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
		$_SESSION["login"] = $row;
	  }
	  echo "<script>window.location.href='home.php';</script>";
	} else {
	  echo "<script>alert('Incorrect email and password.');window.location.href='index.php';</script>";
	}
	$conn->close();
}else{
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Login</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
	  <h2>Login form</h2>
	  <form action="?" method="POST">
		<div class="form-group">
		  <label for="email">Email:</label>
		  <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
		</div>
		<div class="form-group">
		  <label for="pwd">Password:</label>
		  <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="password">
		</div>
		<button type="submit" class="btn btn-primary">Login</button>
		<br>
		<br>
		<a href="registration.php">Create account</a>
	  </form>
	</div>
</body>
</html>
<?php } ?>
In the login page enter credential and click on the login button to log in using PHP session to store user login credentials for checking the user is logged in or not.

Forst time login page check if already login then it will redirect to the home page otherwise login page.

Home:-
Inside the home page use session to check if not logged in then redirect to the login page. otherwise, stay on the home page and show the name of the logged-in user and logout link.
<?php
session_start();
if(empty($_SESSION["login"])){
	echo "<script>window.location.href='index.php';</script>";
}
$user = $_SESSION["login"];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Home</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="jumbotron text-center" style="margin-bottom:0">
	  <h1>Welcome to <?php echo $user['name']?></h1>
	  <p><a href="logout.php">Logout</a></p>
	</div>
</body>
</html>
Logout:-
In logout page use session and unset all session variable after that redirect to the login page that sits.
<?php
session_start();
session_unset();
echo "<script>window.location.href='index.php';</script>";
?>
inside logout also I can use destroy sessions.

Important Points:-
  1. if you want to use password hash then you can use md5 or sha1 or other hashing function when using the registration. Inside login also you can match password using that hash function inside SQL.
  2. You can store more data in the session when login is done.
  3. Also, you can set your own login credentials like mobile, username, and email or more than two using or condition inside the SQL login query.

Post a Comment

0 Comments

Ad Code