I’m busy coding a website for my university project but I’ve ran into some issues regarding php sessions, it seems like the variables gets lost or resets when I navigate to another page and back. For context, the website starts of at index.php (the login page) you type your credentials in and log in, those credentials are cross checked with the database (phpMyAdmin) and if such user is found the userID, name, surname and email gets stored in session variables.
$_SESSION['user_id'] = $user['userID'];
$_SESSION['name'] = $user['name'];
$_SESSION['surname'] = $user['surname'];
$_SESSION['email'] = $user['email'];
After log in you get direct to the dashboard, where there is a navigation bar with link to different pages, one being Shops, where those session variables are required. So if I’m on the dashboard and I only visit shops, not any other page, it allows me to view the shop, If I visit another page like About us and then shops, it kicks me back to login (as it should):
if (!isset($_SESSION['user_id'])) {
header("Location: ../index.php");
exit();
}
$userID = $_SESSION['user_id'];
The above code is responsible for checking if the user logged in.
On all the pages that requires the use of session variables the line of code
session_start();
has been used.
I wrote a piece of code the return the logs when you click on the shops button.
Session Data: Array
(
[user_id] => 1
[name] => tester
[surname] => testing
[email] => [email protected]
)
As you can see the very first time i click on shops it allows me to view it because the session variables are stored. But as soon as I navigate away from the page and revisit it, the log returns this:
Session Data: Array
(
)
Indicating the variables got lost somehow.
I’m using XAMPP to locally host the website for the time being, I’ve double checked the php.ini file to make sure all the relevant information regarding sessions are correct. And applied every piece of advise but non worked.
Ian Ter Haar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.