I have created two pages: a login page and a data display page. The login page checks if the user’s credentials (email and password) exist in the database, and if valid, it redirects the user to the second page. The issue I’m facing is that if someone directly types the URL of the second page into their browser (e.g., http://localhost/fileproject/secondpage.php), the page loads normally without any requirement for login. How can I prevent direct access to the second page without logging in first?
I tried to solve this issue by using PHP sessions. When a user logs in, I store the UserID in the PHP session (using the command $_SESSION[‘UserID’]). On the page that displays the data (i.e., the secondpage), I check whether $_SESSION[‘UserID’] is set. If it is not, then I redirect the user to the login page (admin.php).
Here’s a simplified version of my login page code:
<?php include 'db.php'; session_start(); $conn->set_charset("utf8mb4");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM Users WHERE Email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
$passwordHash = $row['PasswordHash'];
if (password_verify($password, $passwordHash)) {
$_SESSION['UserID'] = $row['UserID'];
header("Location: cmsexotic.php");
exit();
} else {
echo "Wrong combination of email and password.";
}
} else {
echo "Wrong combination of email and password.";
} } ?>
On my second page, I have the following code at the top to check the session:
<?php
session_start();
if (!isset($_SESSION['UserID'])) {
header('Location: admin.php');
exit();
}
?>
Despite this, direct access to the page is still possible. I’ve tried using PHP sessions. When a user logs in, I store the UserID in the PHP session ($_SESSION[‘UserID’]). On the data display page, I check if $_SESSION[‘UserID’] is set and if it is not, then I redirect the user to the login page (admin.php).
I’m not sure why this isn’t working, so I would appreciate any help or suggestions.