article

Wednesday, July 6, 2022

PHP Mysqli Login and Sign Up using jQuery Ajax

PHP Mysqli Login and Sign Up using jQuery Ajax

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

CREATE TABLE `user` (
  `userid` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user` (`userid`, `username`, `password`) VALUES
(1, 'cairocoders', '25f9e794323b453885f5181f1b624d0b');

ALTER TABLE `user`
  ADD PRIMARY KEY (`userid`);

ALTER TABLE `user`
  MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
index.php
//index.php
<?php
	session_start();
	if(isset($_SESSION['user'])){
		header('location:home.php');
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title>PHP Mysqli Login and Sign Up using jQuery Ajax</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"/>
</head>
<body>
<p><center><h1>PHP Mysqli Login and Sign Up using jQuery Ajax </h1></center></p>
<div class="container">
	<div class="row">
		<div id="myalert" style="display:none;">
			<div class="alert alert-info">
				<center><span id="alerttext"></span></center>
			</div>
		</div>
    </div>
	
	<div class="row loginreg" id="loginform">
		<p><h1><i class="fa fa-lock" aria-hidden="true"></i> Login</h1></p>
		<form role="form" id="logform">
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fas fa-user-tie"></i></span>
				<input class="form-control" placeholder="Username" name="username" id="username" type="text" autofocus>
			</div>
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fa fa-key icon"></i></span>
				<input class="form-control" placeholder="Password" name="password" id="password" type="password">
			</div>
			<div class="checkbox">
				  <label><input type="checkbox" value=""/> Remember me</label>
			</div><br />
			<div>
				<button type="button" id="loginbutton" class="btn btn-lg btn-primary btn-block"><i class="fa fa-lock" aria-hidden="true"></i> <span id="logtext">Login</span></button>
			</div>
			
			<center><div style="border:1px solid black;height:1px;width:300px;margin-top:20px;"></div></center>
			 
			<div class="footer">
				<p>Don't have an Account! <a href="#" id="signup">Sign Up Here</a></p>
				<p>Forgot <a href="#">Password?</a></p>
			</div>
		</form>
	</div>	
	
	<div class="row loginreg" id="signupform" style="display:none;">
		<p><h1><i class="fas fa-user-tie"></i> Sign Up</h1></p>
		<form role="form" id="signform">
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fas fa-user-tie"></i></span>
				<input class="form-control" placeholder="Username" name="susername" id="susername" type="text" autofocus>
			</div>
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fa fa-key icon"></i></span>
				<input class="form-control" placeholder="Password" name="spassword" id="spassword" type="password">
			</div>
			<div>
				<button type="button" id="signupbutton" class="btn btn-lg btn-info btn-block"><i class="fa fa-lock" aria-hidden="true"></i> <span id="signtext">Sign Up</span></button>
			</div>
			
			<center><div style="border:1px solid black;height:1px;width:300px;margin-top:20px;"></div></center>
			 
			<div class="footer">
				<p>have an Account! <a href="#" id="login">Login</a></p>
				<p>Forgot <a href="#">Password?</a></p>
			</div>
		</form>
	</div>
</div>
<script src="custom.js"></script>
<style>
  .container{
        border:2px solid blue;
        text-align:center;
        
        height:500px;
        width:400px;
    }
    body{
        padding:70px;
    }
    .loginreg {
        height:90px;
        width:396px;
        background-color:paleturquoise;
    }
	.row p { 
		padding-top:10px;
	}
</style>	
</body>
</html>
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "projectdb");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
login.php
//login.php
<?php 
	include('conn.php');
	session_start();
	if(isset($_POST['username'])){
		$username=$_POST['username'];
		$password=md5($_POST['password']);

		$query=$conn->query("select * from user where username='$username' and password='$password'");

		if ($query->num_rows>0){
			$row=$query->fetch_array();
			$_SESSION['user']=$row['userid']; 
		}
		else{
			?>
  				<span>Login Failed. User not Found.</span>
  			<?php 
		}
	}
?>
signup.php
//signup.php
<?php
	include('conn.php');
	if(isset($_POST['susername'])){
		$username=$_POST['susername'];
		$password=$_POST['spassword'];

		$query=$conn->query("select * from user where username='$username'");

		if ($query->num_rows>0){
			?>
  				<span>Username already exist.</span>
  			<?php 
		}

		elseif (!preg_match("/^[a-zA-Z0-9_]*$/",$username)){
			?>
  				<span style="font-size:11px;">Invalid username. Space & Special Characters not allowed.</span>
  			<?php 
		}
		elseif (!preg_match("/^[a-zA-Z0-9_]*$/",$password)){
			?>
  				<span style="font-size:11px;">Invalid password. Space & Special Characters not allowed.</span>
  			<?php 
		}
		else{
			$mpassword=md5($password);
			$conn->query("insert into user (username, password) values ('$username', '$mpassword')");
			?>
  				<span>Sign up Successful.</span>
  			<?php 
		}
	}
?>
session.php
//session.php
<?php
	session_start();
	include('conn.php');

	$query=$conn->query("select * from user where userid='".$_SESSION['user']."'");
	$row=$query->fetch_array();

	$user=$row['username'];
?>
logout.php
//logout.php
<?php
	session_start();
	session_destroy();
	header('location:index.php');
?>
home.php
//home.php
<!DOCTYPE html>
<html>
<head>
	<title>PHP Mysqli Login and Sign Up using jQuery Ajax</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
	<div style="height:50px;">
	</div>
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
           <h2>Welcome, <?php echo $user; ?>!</h2>
           <a href="logout.php" class="btn btn-danger"> Logout</a>
        </div>
    </div>
</div>
</body>
</html>
script.js
//script.js
$(document).ready(function(){
	//bind enter key to click button
	$(document).keypress(function(e){
    	if (e.which == 13){
    		if($('#loginform').is(":visible")){
    			$("#loginbutton").click();
    		}
        	else if($('#signupform').is(":visible")){
        		$("#signupbutton").click();
        	}
    	}
	});

	$('#signup').click(function(event){
		event.preventDefault();
		$('#loginform').slideUp();
		$('#signupform').slideDown();
		$('#myalert').slideUp();
		$('#signform')[0].reset();
	});

	$('#login').click(function(event){
		event.preventDefault();
		$('#loginform').slideDown();
		$('#signupform').slideUp();
		$('#myalert').slideUp();
		$('#logform')[0].reset();
	});

	$(document).on('click', '#signupbutton', function(){
		if($('#susername').val()!='' && $('#spassword').val()!=''){
			$('#signtext').text('Signing up...');
			$('#myalert').slideUp();
			var signform = $('#signform').serialize();
			$.ajax({
				method: 'POST',
				url: 'signup.php',
				data: signform,
				success:function(data){
					setTimeout(function(){
					$('#myalert').slideDown();
					$('#alerttext').html(data);
					$('#signtext').text('Sign up');
					$('#signform')[0].reset();
					}, 2000);
				} 
			});
		}
		else{
			alert('Please input both fields to Sign Up');
		}
	});

	$(document).on('click', '#loginbutton', function(){
		if($('#username').val()!='' && $('#password').val()!=''){
			$('#logtext').text('Logging in...');
			$('#myalert').slideUp();
			var logform = $('#logform').serialize();
			setTimeout(function(){
				$.ajax({
					method: 'POST',
					url: 'login.php',
					data: logform,
					success:function(data){
						if(data==''){
							$('#myalert').slideDown();
							$('#alerttext').text('Login Successful. User Verified!');
							$('#logtext').text('Login');
							$('#logform')[0].reset();
							setTimeout(function(){
								location.reload();
							}, 2000);
						}
						else{
							$('#myalert').slideDown();
							$('#alerttext').html(data);
							$('#logtext').text('Login');
							$('#logform')[0].reset();
						}
					} 
				});
			}, 2000);
		}
		else{
			alert('Please input both fields to Login');
		}
	});
});

Related Post