Skip to main content

Create secure login script in PHP

Recently more than 10 members asked me how to create secure login script in PHP. So in this article am going to explain you how to create a secure login system using PHP and MYSQL. This type of login system am using in most of the website, if you are using any CMS means no need of this system because CMS have inbuilt login system.

In this method am mainly concentrating on the username and password strings. Am using number of steps to clear the string and prevent the any type of SQL injection to avoid the hacking.

First we will start the session and connecting to the database.

FInd the PHP code below,
//Start session
session_start();

//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = false;

//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
 die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
 die("Unable to select database");
}
PHP

Then we are calling a function called clean. This function is used to sanitize values received from the form to Prevents SQL injection.

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
 $str = @trim($str);
 if(get_magic_quotes_gpc()) {
  $str = stripslashes($str);
 }
 return mysql_real_escape_string($str);
}

//Sanitize the POST values
 $login = clean($_POST['login']);
 $password = clean($_POST['password']);

//Input Validations
if($login == '') {
 $errmsg_arr[] = 'Login ID missing';
 $errflag = true;
}
if($password == '') {
 $errmsg_arr[] = 'Password missing';
 $errflag = true;
}

//If there are input validations, redirect back to the login form
if($errflag) {
 $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
 session_write_close();
 header("location:index.php?msg=error");
 exit();
}
PHP

Now we are ready to pass the string value to the query to check whether the record. If found we can create session variables and redirect user to logged in page.

//Create query
$qry="select * from admin_log where username='".$login."' and password='".$password."'";
$result=mysql_query($qry);

//Check whether the query was successful or not
if($result) {
 if(mysql_num_rows($result) == 1) {
  //Login Successful
  session_regenerate_id();
  $member = mysql_fetch_assoc($result);

  $_SESSION['SESS_MEMBER_ID'] = $member['id'];
  $_SESSION['SESS_FIRST_NAME'] = $member['login'];
  session_write_close();

  header("location: home.php");
  exit();
 }else {
  //Login failed
  header("location: index.php?msg=error");
  exit();
 }
}else {
 die("Query failed");
}
PHP
So by using this system we can prevent the SQL injection and make an secured login script. Hope this will help you!