I am trying to make login script safe to stop hacking of my website. I am trying to use mysql_real_escape_string in my script can anyone guide me if i am wrong in this.
Here is my code
<?php
session_start();
include("lib/conn.php");
?>
<?php
$email=$_POST['user'];
$password=$_POST['password'];
if ($email && $password){
$query = "SELECT * FROM register WHERE email = '$email' AND password= '$password' and status = '1'";
mysql_real_escape_string($email);
mysql_real_escape_string($password);
$result = mysql_query( $query ) or die ("didn't query");
$num = mysql_num_rows( $result );
if ($num == 1){
$_SESSION['ocer']=$email;
header("Location: admin.php");
}
else {
header("Location: index.php?l=1");
}
}
?>
First of all. Use PDO with bind parameter. Then you don't have to worry about injections.
mysql_real_escape_string returns the escaped string and should be used before constructing your query. Use is as so:
$password = mysql_real_escape_string($password);
Also. Don not retrieve by password and email. retrieve password by email and validate that there the same.
Hope it helps
Here is the example:
session_start();
include("lib/conn.php");
//using isset to avoid warnings.
$email = isset($_POST['user']) ? $_POST['user'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
//check if values are not null
if ($email !== null && $password !== null){
//escape email
$email = mysql_real_escape_string($email);
//retrieve password by email and limit 1 result
$query = "SELECT password FROM register WHERE email = '{$email}' and status = '1' LIMIT 1";
//run query
$result = mysql_query( $query ) or die ("didn't query");
//validate if query run correctly
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
//fetch row
$row = mysql_fetch_row($result);
//validate result
if ($row['password'] == $password){
$_SESSION['ocer']=$email;
header("Location: admin.php");
} else {
header("Location: index.php?l=1");
}
}