Having problem in login form

each time i input wrong username and password it display 1 at the same page in login form instead of showing wrong username and password.

<?php
session_start(); // Starting Session

if (isset($_SESSION['username'])){
    header('Location: profile.php');
}

if (isset($_POST['submit'])) {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];

//check if textbox is empty.
if (empty($username) || empty($password)){
    echo ("<script language='javascript'>
             window.alert('Fill All Fields.')
             window.location.href='javascript:history.back()'
           </script>");
           exit;
}

// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("127.0.0.1", "root", "");
$db = mysql_select_db("david_car", $connection);

// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$login = mysql_query("SELECT * FROM data_time WHERE username = '".$username."' AND password = '".$password."' ")or die(mysql_close());
$res = mysql_num_rows($login)or die(mysql_close());

if ($res > 0){
    $_SESSION['username'] = $_POST['username'];
    header('Location: profile.php');
    die();
    
}else{
 echo "wrong username and password";
}

}

?>

<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<div id="login">
<h2>Login Form</h2>
<form action="login.php" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value="Login">
</form>
</div>
</div>
</body>
</html>

Why are you usinf stripslashes and the soon to be deleted mysql_real_escape_string on the password field - once you feed it to password_hash() it will be safe to insert into the database using mysqli or pdo without needing to be escaped. Anyway escaping anything to go in the database is now obsolete since both mysqli and pdo support prepare statements that keep the data separate from the sql (the mysql interface your code is using was flagged as obsolete about five or so years back and is going to be deleted any day now).

1 Like

One minor thing that I notice, I wouldn’t put a placeholder in the password input field, some people get nervous when they see something in the password field. Besides people will know what to put in there if it’s blank.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.