Create User Registration and Login Script with PHP & MySQL

 

Today I am going to discuss how to create a user registration and login script using PHP and MySQL. As you have already seen on the Web/Mobile App, most website requires a user registration and login page to access their resources. When you create your registration and login page you should always take care of your website from hackers.So lets start step by step how to do this in PHP & MySQL.

config.php
This is your database configuration file.

<?php
define('HOST_NAME','localhost'); //Put your host name
define('DATABASE_NAME','db_name');//Put your database name
define('DATABASE_USER_NAME','db_user_name'); //put your database user name
define('DATABASE_PASSWORD',''); //Put your password here
$connection=mysqli_connect(HOST_NAME,DATABASE_USER_NAME,DATABASE_PASSWORD,DATABASE_NAME);

if (mysqli_connect_errno()) {
    die(mysqli_connect_error());
}
?>

function.php
Define all function which is required so we dont need to write the same piece of code again and again.

<?php
function TrimText($txt){
	return trim($txt);	
}

function RealEscape($connection,$txt){
	return mysqli_real_escape_string($connection,$txt);
}

function AddSlash($txt){
	return addslashes($txt);
}

function StripSlash($txt){
	return addslashes($txt);
}

function HtmlentitiesText($txt){
	return htmlentities($txt);
}

/*Generate Form Token*/
function generateCSRFToken($form_name) {    
	$token = md5(uniqid(time(),true)); //Generate a unique value
	//Generate a CSRF Token and store it in a session variable which will generate
	// like $_SESSION['CSRF_TOKEN_XXX']=<Random String Value>
	$_SESSION['CSRF_TOKEN'.strtoupper(trim($form_name))] = $token; 			
	return $token;	
}

function verifyCSRFToken($form_name,$input_hidden) {		
	// check if input_hidden hidden field is exist
	if(!isset($_POST[trim($input_hidden)])) {
		die("Token field does not exist.");
	}
	
	// check if a CSRF Token session exist else return error
	if(!isset($_SESSION['CSRF_TOKEN'.strtoupper(trim($form_name))])) { 
		die("CSRF Token does not exist.");		
	}
	
	//Check input hidden field and session csrf token value is same
	if ($_POST[trim($input_hidden)] !== $_SESSION['CSRF_TOKEN'.strtoupper(trim($form_name))]) {
		die("Invalid Token");		
	}			
	return true;		
}
?>

How to Create User Registration with Captcha Security Code?

Before any user can login into your website, he/she must be a registered user on your website. So here we will see how user registration with captcha security will work in PHP.

register.php
Below are the user register page code.

<?php
session_start();
if(isset($_SESSION['UserId']) && $_SESSION['UserId']>0){
	header("location:profile.php");
    exit();	
}
require('config.php');
require('function.php');
$ErrorArray=array();
$error_msg='';
if(isset($_POST['submit']) && $_SERVER['REQUEST_METHOD']=="POST"){
	
	if(isset($_POST["uname"]) && TrimText($_POST["uname"])==''){
		 $ErrorArray[]="Enter your name.";
	}
	
	if(isset($_POST["email"]) && TrimText($_POST["email"])==''){
		 $ErrorArray[]="Enter your email address.";
	}else if (filter_var(TrimText($_POST['email']), FILTER_VALIDATE_EMAIL) === false) {
	  	$ErrorArray[]="Enter a valid email address.";
	}else{ //Check if this email address is already exist in the database
		$sql="SELECT email FROM user WHERE email='".RealEscape($connection,TrimText($_POST['email']))."'";
		$result=mysqli_query($connection,$sql);
		if(mysqli_num_rows($result)>0){
			$ErrorArray[]="Email address already exist.";
		}
	}
	
	if(isset($_POST["pwd"]) && TrimText($_POST["pwd"])==''){
		 $ErrorArray[]="Enter your password.";
	}
	
	if(isset($_FILES["profile_img"]) && count($_FILES["profile_img"])>0){
		 if($_FILES["profile_img"]['error']==0){
			 if (exif_imagetype($_FILES["profile_img"]['tmp_name'])==false) {
				$ErrorArray[]="Please upload a valid image.";
			 }
		}		 
	}
	
	if(isset($_POST["security_code"]) && TrimText($_POST["security_code"])==''){
		 $ErrorArray[]="Enter security code.";
	}else if(TrimText($_POST["security_code"])!=$_SESSION['CAPTCHA_CODE']){
		 $ErrorArray[]="Invalid security code.";	
	}
	
	if(count($ErrorArray)>0){
		$error_msg=implode('<br />',$ErrorArray);
	}else{
		$user_img_name='';
		if(isset($_FILES["profile_img"]) && count($_FILES["profile_img"])>0){
			 if($_FILES["profile_img"]['error']==0){
				 $user_img_name=$_FILES["profile_img"]['name'];
				 move_uploaded_file($_FILES["profile_img"]['tmp_name'],'upload/'.$user_img_name);				 
			}		 
		}
	
		$username=AddSlash(TrimText($_POST["uname"]));
		$email=AddSlash(TrimText($_POST["email"]));
		$pwd=AddSlash(TrimText($_POST["pwd"]));
		$sql="INSERT INTO user (uname,email,password,profile_img,status) VALUES('".$username."','".$email."','".md5($pwd)."','".$user_img_name."','1')";
		$result=mysqli_query($connection,$sql);
		if(mysqli_affected_rows($connection)>0){
			$_SESSION['UserId']=mysqli_insert_id($connection);			
			header("location:profile.php");
			exit();
		}
	}
}

/*This is an example i have hard coded you can make it dynamic*/
$_SESSION['CAPTCHA_CODE']='9504';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>User Registration Script</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td colspan="2"><span class="register">User Registration</span></td>
  </tr>
  <?php
  if($error_msg!=''){?>
      <tr>
       <td colspan="2"><div class="error"><?php echo $error_msg;?></div></td>
      </tr>
  <?php 
  }
  ?>
  <tr>
    <td>Name</td>
    <td><input name="uname" id="uname" type="text" value="<?php if(isset($_POST['uname'])){echo HtmlentitiesText($_POST['uname']);}?>" /></td>
  </tr>
  <tr>
    <td>Email Address</td>
    <td><input name="email" id="email" type="text" value="<?php if(isset($_POST['email'])){echo HtmlentitiesText($_POST['email']);}?>"/></td>
  </tr>
  <tr>
    <td>Password</td>
    <td><input name="pwd" id="pwd" type="password" value="<?php if(isset($_POST['pwd'])){echo HtmlentitiesText($_POST['pwd']);}?>"/></td>
  </tr>  
  <tr>
    <td>User Profile</td>
    <td><input name="profile_img" id="profile_img" type="file" /></td>
  </tr>
  <tr>
    <td>Security Code</td>
    <td><input name="security_code" id="security_code" type="text"/>&nbsp;<img src="captcha.png" /></td>
  </tr>
  <tr>
    <td></td>
    <td><input name="submit" type="submit" value="Register" /></td>
  </tr>  
</table>
</form>
</body>
</html>

In the above code we have 5 fields. I have added one input file type for upload user image. So you can get an idea how to upload image in php. To prevent any automatic bot/script you can add a captcha security image in your form. Here, I have included an image in the tag for captcha image and stored the security code in the session variable $_SESSION[‘CAPTCHA_CODE’]. The above code also prevents the user from registering with same email-id again. There should be a folder to upload user image i.e “upload” folder is used in the above code.

Once user submits the form it performs all validation. If there is any error then it displays the error message to the user else saves the data in the database and stores the last inserted id into “$_SESSION[‘UserId’]” session variale, so we can retrieve the user data on profile page.

profile.php
Displaying the current logged in user data which user has submited during the tome of registration.

<?php
session_start();
require('config.php');
require('function.php');
$UserData=array();
$sql="SELECT * FROM user WHERE uid='".(int)$_SESSION['UserId']."' AND status='1'";
$result=mysqli_query($connection,$sql);
if(mysqli_num_rows($result)>0){
	$UserData=mysqli_fetch_array($result);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Profile</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td><span class="register">Profile Details</span></td>
    <td align="right"><a href="logout.php">Logout</a></td>
  </tr>  
  <tr>
    <td>Name</td>
    <td><?php if(isset($UserData['uname'])){echo HtmlentitiesText(StripSlash($UserData['uname']));}?></td>
  </tr>
  <tr>
    <td>Email Address</td>
    <td><?php echo HtmlentitiesText(StripSlash($UserData['email']));?></td>
  </tr>    
  <tr>
    <td>Profile Image</td>
    <td>
	<?php 
	if($UserData['profile_img']!=''){
		if(file_exists('upload/'.$UserData['profile_img'])){?>
			<img src="upload/<?php echo $UserData['profile_img'];?>" width="50" height="50" />
		<?php
        }
	}	
	?>
    </td>
  </tr>    
</table>
</form>
</body>
</html>

How to Create Secure Web Login Script

Now we will see how to create secure login script.When you create login page always take care of security issues like adding some token in the page or add captcha code or use mysqli_real_escape_string MySQL function to prevent from SQL Injection or from outside intruder or automatic bot/script. In the login page I have called a function “generateCSRFToken” which generates random string as a token for your form and when you post the page it checks whether session token variable matches with input security token value.If session token value and input hidden token value mismatch then the user cannot login to his panel and “Invalid Token” message is displayed to the user.

login.php
Below are the codes of user login script.

<?php
session_start();
if(isset($_SESSION['UserId']) && $_SESSION['UserId']>0){
	header("location:profile.php");
    exit();	
}
require('config.php');
require('function.php');
$ErrorArray=array();
$error_msg='';
if(isset($_POST['submit']) && $_SERVER['REQUEST_METHOD']=="POST"){
	
	if(isset($_POST["email"]) && TrimText($_POST["email"])==''){
		 $ErrorArray[]="Enter your email address.";
	}else if (filter_var(TrimText($_POST['email']), FILTER_VALIDATE_EMAIL) === false) {
	  	$ErrorArray[]="Enter a valid email address.";
	}
	
	if(isset($_POST["pwd"]) && TrimText($_POST["pwd"])==''){
		 $ErrorArray[]="Enter your password.";
	}
	
	//For Verify CSRF Token
	verifyCSRFToken('login_frm','login');
	
	if(count($ErrorArray)>0){
		$error_msg=implode('<br />',$ErrorArray);
	}else{
		
		//Check if this email address is already exist in the database
		$email=RealEscape($connection,TrimText($_POST["email"]));
		$pwd=RealEscape($connection,TrimText($_POST["pwd"]));
		$sql="SELECT uid,uname FROM user WHERE email='".$email."' AND password='".md5($pwd)."' AND status='1'";
		$result=mysqli_query($connection,$sql);
		if(mysqli_num_rows($result)>0){
			$UserData=mysqli_fetch_array($result);
			$_SESSION['UserId']=$UserData['uid'];			
			header("location:profile.php");
			exit();
		}else{
			$error_msg="Invalid email address/password or your account is disable.";
		}		
	}
}

$CSRFToken=generateCSRFToken('login_frm');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>User Login Script</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form action="" name="login_frm" method="post" enctype="multipart/form-data">
<input type="hidden" name="login" value="<?php echo $CSRFToken;?>" />
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td colspan="2"><span class="register">Login</span></td>
  </tr>
  <?php
  if($error_msg!=''){?>
      <tr>
       <td colspan="2"><div class="error"><?php echo $error_msg;?></div></td>
      </tr>
  <?php 
  }
  ?>  
  <tr>
    <td>Email Address</td>
    <td><input name="email" id="email" type="text" value="<?php if(isset($_POST['email'])){echo HtmlentitiesText($_POST['email']);}?>" /></td>
  </tr>
  <tr>
    <td>Password</td>
    <td><input name="pwd" id="pwd" type="password" value="<?php if(isset($_POST['pwd'])){echo HtmlentitiesText($_POST['pwd']);}?>"/></td>
  </tr>    
  <tr>
    <td></td>
    <td><input name="submit" type="submit" value="Login" /></td>
  </tr>  
</table>
</form>
</body>
</html>

Finally after user logs-in to the panel than there should be an option to logout from the panel. Below are the codes for user logout.
logout.php

<?php
session_start();
session_destroy();
header("location:register.php");
exit();
?>

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories