This is my login.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM admin WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
$_SESSION['username'] = $username;
header("Location: dashboard.php");
exit();
} else {
$error_message = "Invalid username or password";
}
$stmt->close();
}
Below is my dashboard.php:
<?php
session_start();
if (isset($_SESSION['username'])) {
echo "Logged in as: " . $_SESSION['username'];
} else {
echo "You are not logged in.";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="another_page.php">Link to another page</a>
</body>
</html>
And below is my another_page.php:
<?php
session_start();
if (!isset($_SESSION['username'])) {
echo "No session found. Please log in first.";
} else {
echo "Welcome ". $_SESSION['username'];
}
?>
Basically I am logging and after successful login, i am landed to dashboard.php and here on this page, the $_SESSION[‘username’] is accessible, but when I click the link to another_page.php, then on that page, the session variable is not accessible.
Please let me know where i am wrong.
2
Answers
Your issue likely stems from not calling
session_start()
at the very beginning of your PHP scripts(at least from what you posted), and like Alex Howansky commented, you should usepassword_hash()
andpassword_verify()
when handling passwords.Here’s a slight rewrite with those two things in mind, as well as a few minor improvements:
login.php
dashboard.php
another_page.php
additional tip: make sure that there are no outputs before
session_start()
andheader()
calls, even a single space can bork session handling and redirection.edit: You could also use
<?=
instead of<?php echo
, but I don’t really like itThe only issue is you are not starting session at start
login.php
file.