3
I’m, for the first time, using Prepared statements.
I am confused and do not know why is not returning the authenticated user.
Follow my code:
index php.
<form method="post" action="php/login.php">
<div class="form-group">
<input class="form-control" type="text" name="username" placeholder="Username" required>
</div>
<div class="form-group">
<input class="form-control" type="password" name="password" placeholder="Password" required>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="login" value="Login">
</div>
</form>
login.php
<?php
require_once "../functions.php";
db_connect();
$sql = "SELECT id, username, password FROM users WHERE username = ?";
$statement = $conn->prepare($sql);
$statement->bind_param('s', $_POST['username']);
$statement->execute();
$statement->store_result();
$statement->bind_result($id, $username, $password);
$statement->fetch();
if ($statement->execute()) {
if(password_verify($_POST['password'], $password)) {
$_SESSION['user_id'] = $id;
$_SESSION['user_username'] = $username;
redirect_to("/home.php");
} else {
redirect_to("../index.php?login_error=true");
}
} else {
echo "Error: " . $conn->error;
}
functions.php
<?php
session_start();
function db_connect() {
global $conn; // db connection variable
$db_server = "localhost";
$username = "root";
$password = "xxxxxxxxx";
$db_name = "xxxxxxxxxx";
// create a connection
$conn = new mysqli($db_server, $username, $password, $db_name);
// check connection for errors
if ($conn->connect_error) {
die("Error: " . $conn->connect_error);
}
}
function redirect_to($url) {
header("Location: " . $url);
exit();
}
function is_auth() {
return isset($_SESSION['user_id']);
}
function check_auth() {
if(!is_auth()) {
redirect_to("../index.php?logged_in=false");
}
}
The error returned is:
Invalid username or password!
Which is a message displayed on the page index.php
.
Thank you Lipespry, it returns " Invalid username or password! "
– Sergio Guerjik
that’s right Lipespry index.php? login_error=true
– Sergio Guerjik
I added the information you went through the comments to your question. Be sure to provide that kind of information in your next questions. Furthermore, you can delete your comments, as I did with mine. Tmj!
– LipESprY