I created some sort of "blog" application, a website that offers users the ability to post articles that are shown on a specific articles.php
page.
Because of that, I also created a "login system", and to make it more secure, I hashed the passwords and used mysqli_real_escape_string()
, just to find out that the function doesn't have anything to do with security. And that's why I chose to learn how to use prepared statements
.
Anyways, that's how my users
table looks like:
username
- varchar(30)
and
password
- varchar(60)
... and that's my login form:
<form action="" method="POST">
<input type="textbox" name="user" placeholder="Username" class="textbox" required>
<input type="password" name="pass" placeholder="Password" class="textbox" required>
<input type="submit" name="btn" value="Login" class="btn">
</form>
... and that's the part of the code where I'm trying to use the prepared statements (it worked before replacing everything with the prep. statements):
if (isset($_POST['btn']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$stmt = $con->prepare("SELECT * FROM users WHERE username = ? LIMIT 1");
$stmt->bind_param("s", $user);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_array();
$num = $stmt->num_rows();
if ($num) {
if (password_verify($pass, $row['password'])) {
echo "Successfully logged in.";
$_SESSION['logged'] = true;
$_SESSION['username'] = $user;
setcookie("username", $user, time() + 86400*2);
setcookie("password", $pass, time() + 86400*2);
header("Location: index.php");
}else
echo "Password is incorrect.";
} else
echo "Username doesn't exist.";
$stmt->close();
}
The problem is, when I type in mmateas
or admin
, I can see the message:
Username doesn't exist
shown on my webpage.
What did I do wrong? If anything's wrong with the question, please leave a comment and I'll edit it as soon as possible. Thank you!
Edit: I realized I forgot to assign values to $user
and $pass
, before starting the prep. statements. I've added these two lines of code
$user = $_POST['user'];
$pass = $_POST['pass'];
but I still receive the same error.