It's very important to secure your login system which can be attacked by various attacking methode. SQL Injection is the common attacking methode that is used to gain the login authetication of the login system.
One of the most common SQL Injection look like this:
' or '1'='1' --
It's very unsecured to use the simple login verification methode to login in your system while currently most online web login system use the more secured way of login.
This tutorial will help to secure your login sytem by just implementing the mysqli_prepare to your login function.
To begin, we first need to have the connection to the database.
$dbhost = "localhost"; $dbuser = "root"; $dbpass = "pass"; $dbname = "dbname"; $conn = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die("Error " . mysqli_error($conn));
Now we have the database connection. What we will do now is making the login condition.
if ($stmt = mysqli_prepare($conn, "SELECT id,username FROM tbluser WHERE BINARY username=? AND password=? AND active=? LIMIT 1")) { //create a prepared statement $active = 1; mysqli_stmt_bind_param($stmt, "ssi", $myusername,$encriptedpass,$active); mysqli_stmt_execute($stmt); mysqli_stmt_store_result($stmt); $count = mysqli_stmt_num_rows($stmt); if($count==1){ session_register("userid");//for PHP 5.4 use session_start() instead; mysqli_stmt_bind_result($stmt, $get_userid, $get_username); while(mysqli_stmt_fetch($stmt)){ $_SESSION['userid']=$get_userid; $_SESSION['username']= $get_username; } mysqli_stmt_close($stmt); mysqli_close($conn); //do something when login is successful } else { mysqli_stmt_close($stmt); mysqli_close($conn); //do something when login failed/invalid } }
We may have the data like username and password from the login form, then we use function mysqli_stmt_bind_param to get those data for the query where the verificated data are not placed directly in the SQL statement (the question mark are used instead).
To verify the login, we count the row of the data returned from the query. If one row is found, we make the login successful and if there is no row found, we make the login failed.
To retrieve the data from the above function and assign those data to session, we use the below lines:
mysqli_stmt_bind_result($stmt, $get_userid, $get_username); while(mysqli_stmt_fetch($stmt)){ $_SESSION['userid']=$get_userid; $_SESSION['username']= $get_username; }
That's it! the secured login is implemented.