Saturday, 13 January 2018

How to authenticate a user and create session in PHP ?

User authentication is very essential part of any web application. There may be many kind of user authentication are available in web technology, but form based user authentication is very common and secure.

Now here I am telling about form based user authentication in PHP and session creation. Here I pre- assume that you all are aware of database, and pre-requisite is a user table with user data. it may be like this -



Now I also assume that you know that how to create login form and perform a action on it. But again I am giving screen shot of login page code and its output.



output looks looks like -


Above is database design and form design.

Now come to the PHP programming, how would you authenticate the user and create a session for him?

Here is the full code to authenticate user and create his session.

<?php
session_start();

// Connect to server and select databse.

  $host="localhost";// Host name
  $username="root";// Mysql username
  $password="aarvindd";// Mysql password
  $db_name="e-cert";// Database name
  $con=mysqli_connect("$host", "$username", "$password")or die("cannot connect");
  mysqli_select_db($con,"$db_name")or die(mysqli_error());

// To protect MySQL injection(<a href="http://us.php.net/mysql_real_escape_string">more detail about MySQL injection</a>)

   $myusername = mysqli_real_escape_string($con,$myusername);
  $mypassword = mysqli_real_escape_string($con,$mypassword);

if (isset($_POST['Submit'])) {
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
  $result=mysqli_query($con,$sql);
  
// Mysql_num_row is counting table row
  $count=mysqli_num_rows($result);
    
  // If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// create session
 $_SESSION['user'] =$myusername;
//redirect user to his page
  header("location:adminhome.php");
}

  else {
  header("location:index.php?ll=Invalid Credentials, please try again.");
  }
  }
  
  ?>



No comments:

Post a Comment

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...