article

Thursday, June 2, 2022

Login and Register using PDO PHP Mysql

Login and Register using PDO PHP Mysql

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

font-awesome
https://cdnjs.com/libraries/font-awesome

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `reg_date` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);
  
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

Database Connection
conn.php
//conn.php
<?php
 
$host = 'localhost';
$db   = 'devprojectdb';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
 
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $user, $pass, $options);
 
?>
Login Form
index.php
//index.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Login and Register using PDO PHP Mysql</title>
	<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
	<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js"></script>
</head>
<body>
<div class="container">
	<h1 class="text-center" style="margin-top:30px;">Login and Register using PDO PHP Mysql</h1>
	<hr>
	<div class="row justify-content-md-center">
		<div class="col-md-5">
			<?php 
				if(isset($_SESSION['error'])){
					echo "
						<div class='alert alert-danger text-center'>
							<i class='fas fa-exclamation-triangle'></i> ".$_SESSION['error']."
						</div>
					";
 
					//unset error
					unset($_SESSION['error']);
				}
 
				if(isset($_SESSION['success'])){
					echo "
						<div class='alert alert-success text-center'>
							<i class='fas fa-check-circle'></i> ".$_SESSION['success']."
						</div>
					";
 
					//unset success
					unset($_SESSION['success']);
				}
			?>
			<div class="card">
				<div class="card-body">
				    <h5 class="card-title text-center">Sign in your account</h5>
				    <hr>
				    <form method="POST" action="login.php">
				    	<div class="mb-3">
						  	<label for="email">Email</label>
						    <input class="form-control" type="email" id="email" name="email" value="<?php echo (isset($_SESSION['email'])) ? $_SESSION['email'] : ''; unset($_SESSION['email']) ?>" placeholder="input email" required>
						</div>
						<div class="mb-3">
						  	<label for="password">Password</label>
						    	<input class="form-control" type="password" id="password" name="password" value="<?php echo (isset($_SESSION['password'])) ? $_SESSION['password'] : ''; unset($_SESSION['password']) ?>" placeholder="input password" required>
						</div>
				    <hr>
				    <div>
				    	<button type="submit" class="btn btn-primary" name="login"><i class="fas fa-sign-in-alt"></i> Login</button>
				    	<a href="register_form.php">Register a new account</a>
				    </div>
					</form>
				</div>
			</div>
		</div>
	</div>
</body>
</html>
Login Script
login.php
//login.php
<?php
	//start PHP session
	session_start();
 
	//check if login form is submitted
	if(isset($_POST['login'])){
		//assign variables to post values
		$email = $_POST['email'];
		$password = $_POST['password'];
 
		//include our database connection
		include 'conn.php';
 
		//get the user with email
		$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
 
		try{
			$stmt->execute(['email' => $email]);
 
			//check if email exist
			if($stmt->rowCount() > 0){
				//get the row
				$user = $stmt->fetch();
 
				//validate inputted password with $user password
				if(password_verify($password, $user['password'])){
					//action after a successful login
					$_SESSION['success'] = 'User verification successful';
				}
				else{
					//return the values to the user
					$_SESSION['email'] = $email;
					$_SESSION['password'] = $password;
 
					$_SESSION['error'] = 'Incorrect password';
				}
 
			}
			else{
				//return the values to the user
				$_SESSION['email'] = $email;
				$_SESSION['password'] = $password;
 
				$_SESSION['error'] = 'No account associated with the email';
			}
 
		}
		catch(PDOException $e){
			$_SESSION['error'] = $e->getMessage();
		}
 
	}
	else{
		$_SESSION['error'] = 'Fill up login form first';
	}
 
	header('location: index.php');
?>
Registration form
register_form.php
//register_form.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Login and Register using PDO PHP Mysql</title>
	<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
	<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js"></script>
</head>
<body>
<div class="container">
	<h1 class="text-center" style="margin-top:30px;">Login and Register using PDO PHP Mysql</h1>
	<hr>
	<div class="row justify-content-md-center">
		<div class="col-md-5">
			<?php
				if(isset($_SESSION['error'])){
					echo "
						<div class='alert alert-danger text-center'>
							<i class='fas fa-exclamation-triangle'></i> ".$_SESSION['error']."
						</div>
					";
 
					//unset error
					unset($_SESSION['error']);
				}
 
				if(isset($_SESSION['success'])){
					echo "
						<div class='alert alert-success text-center'>
							<i class='fas fa-check-circle'></i> ".$_SESSION['success']."
						</div>
					";
 
					//unset success
					unset($_SESSION['success']);
				}
			?>
			<div class="card">
				<div class="card-body">
				    <h5 class="card-title text-center">Register a new account</h5>
				    <hr>
				    <form method="POST" action="register.php">
				    	<div class="mb-3 row">
						  	<label for="email" class="col-sm-3 col-form-label">Email</label>
						  	<div class="col-sm-9">
						    	<input class="form-control" type="email" id="email" name="email" value="<?php echo (isset($_SESSION['email'])) ? $_SESSION['email'] : ''; unset($_SESSION['email']) ?>" placeholder="input email" required>
						  	</div>
						</div>
						<div class="mb-3 row">
						  	<label for="password" class="col-sm-3 col-form-label">Password</label>
						  	<div class="col-sm-9">
						    	<input class="form-control" type="password" id="password" name="password" value="<?php echo (isset($_SESSION['password'])) ? $_SESSION['password'] : ''; unset($_SESSION['password']) ?>" placeholder="input password" required>
						  	</div>
						</div>
						<div class="mb-3 row">
						  	<label for="confirm" class="col-sm-3 col-form-label">Confirm</label>
						  	<div class="col-sm-9">
						    	<input class="form-control" type="password" id="confirm" name="confirm" value="<?php echo (isset($_SESSION['confirm'])) ? $_SESSION['confirm'] : ''; unset($_SESSION['confirm']) ?>" placeholder="re-type password">
						  	</div>
						</div>
				    <hr>
				    <div>
				    	<button type="submit" class="btn btn-success" name="register"><i class="far fa-user"></i> Signup</button>
				    	<a href="index.php">Back to login</a>
				    </div>
					</form>
				</div>
			</div>
		</div>
	</div>
</body>
</html>
Registraition Script
register.php
//register.php
<?php
	//start PHP session
	session_start();
 
	//check if register form is submitted
	if(isset($_POST['register'])){
		//assign variables to post values
		$email = $_POST['email'];
		$password = $_POST['password'];
		$confirm = $_POST['confirm'];
 
		//check if password matches confirm password
		if($password != $confirm){
			//return the values to the user
			$_SESSION['email'] = $email;
			$_SESSION['password'] = $password;
			$_SESSION['confirm'] = $confirm;
 
			//display error
			$_SESSION['error'] = 'Passwords did not match';
		}
		else{
			//include our database connection
			include 'conn.php';
 
			//check if the email is already taken
			$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
			$stmt->execute(['email' => $email]);
 
			if($stmt->rowCount() > 0){
				//return the values to the user
				$_SESSION['email'] = $email;
				$_SESSION['password'] = $password;
				$_SESSION['confirm'] = $confirm;
 
				//display error
				$_SESSION['error'] = 'Email already taken';
			}
			else{
				//encrypt password using password_hash()
				$password = password_hash($password, PASSWORD_DEFAULT);
 
				//insert new user to our database
				$stmt = $pdo->prepare('INSERT INTO users (email, password) VALUES (:email, :password)');
 
				try{
					$stmt->execute(['email' => $email, 'password' => $password]);
 
					$_SESSION['success'] = 'User verified. You can <a href="index.php">login</a> now';
				}
				catch(PDOException $e){
					$_SESSION['error'] = $e->getMessage();
				}
 
			}
 
		}
 
	}
	else{
		$_SESSION['error'] = 'Fill up registration form first';
	}
 
	header('location: register_form.php');
?>

Related Post