I'm totally new with PHP. I am building a PHP login system with session. The idea is that the user enters their username and password. Then they are redirected to a page that is locked, which links to other locked pages. Locked pages have a script that checks if a session is started. If not, the user is redirected to the login page. The issue that I'm facing is that the system basically is not working-no errors, no alert messages, which I put for debug purposes, nothing that indicates that the script is functioning. The only thing that can be considered is that the login form refreshes the page but I still expect to see an alert box just after the code executing.
This is my login script(index.php)(totally not copy-pasted from random tutorial site)(Live url: http://daaseed.com/Player/):
<form action="" method="post">
<input type="text" name="username" placeholder="Enter your username" required>
<input type="password" name="password" placeholder="Enter your password" required>
<input type="submit" value="Submit"> </form>
<?php
// Always start this first
session_start();
if ( ! empty( $_POST ) ) {
if ( isset( $_POST['username'] ) && isset( $_POST['password'] ) ) {
// Getting submitted user data from database
$con = new mysqli("sfconsul.dot5hostingmysql.com ", "Nasko", "Nasko", "Nasko");
$stmt = $con->prepare("SELECT * FROM Nasko WHERE username = ?");
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_object();
// Verify user password and set $_SESSION
if ( password_verify( $_POST['password'], $user->password ) ) {
$_SESSION['user_id'] = $user->ID;
}
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
alert("Hello World");
}
}
?>
This is the verifying code that checks if a session is set or not:
<?php
// You'd put this code at the top of any "protected" page you create
// Always start this first
session_start();
if ( isset( $_SESSION['user_id'] ) ) {
// Grab user data from the database using the user_id
// Let them access the "logged in only" pages
alert("Done");
} else {
// Redirect them to the login page
header("Location: http://daaseed.com/Player/");
}
This is the screenshot from the login page after entering data and pressing the button
The locked page shows the content without checking for session (based on my opinion since not alert box is displayed).
As you can see there is some issue or issues with the code that I cannot find the solution to. How to make the above code work successfully?