英文:
PHP session not saved when navigating between pages on my website
问题
It appears that you're experiencing an issue with PHP sessions not being saved as you navigate through the pages of your website. This issue seems to revolve around the session management in your PHP code.
Here are some potential reasons and solutions to consider:
-
Check Session Start: Ensure that
session_start()
is called at the beginning of each page where you want to use sessions. This function initializes the session and should be placed before any HTML or other output. -
Session.save_path: You mentioned that the
session.save_path
setting in yourphp.ini
files is set to"tmp/"
. Make sure this directory exists and is writable by the PHP process. You might want to specify an absolute path instead of a relative one. -
Session Destroy: In your code, there's a commented-out section that destroys the session after 30 minutes of inactivity. Make sure this is not causing the issue. You might consider removing or modifying this section as needed.
-
Error Logging: You are using error logging to check session status and the save path. While this is helpful for debugging, ensure that error logs are accessible and correctly configured.
-
Redirect Logic: Check your redirect logic after successful login. Ensure that it properly sets
$_SESSION['logged_admin']
and redirects the user to the admin dashboard. -
Session ID: Make sure you are not unintentionally changing the session ID anywhere in your code. Session hijacking can occur if the session ID changes unexpectedly.
-
Testing on Different Environments: Test your code on different environments to rule out any server-specific issues.
-
Session.auto_start: Ensure that
session.auto_start
is not enabled in your PHP configuration, as it can interfere with manual session management. -
Clear Browser Cache: Sometimes, browser caching can cause unexpected behavior. Try accessing your site in an incognito/private browsing window to see if the issue persists.
-
PHP Version Compatibility: Ensure that your code is compatible with the PHP version you are using (PHP 8.1.0 in your case).
Remember to carefully review your PHP code to identify any issues related to session handling and redirection. Additionally, consider using PHP's built-in functions like session_id()
and session_name()
to inspect the session ID and name, respectively, for debugging purposes.
Please review your code based on these suggestions to resolve the session-related issues you're encountering.
英文:
Why isn't my php session saved as i navigate through the pages of my website ?
I am creating a website that uses a simple username-password couple to allow admins to authentify themselves on a log in page. For that, first a session is created when the user arrives upon the main page, then as they click on the log in button they're redirected to a form to enter their username and password, then the form is sent via POST methode to another page that veryfies if the username and passwords are valid, putting in the session a variable containing the username of the logged-in admin, before redirecting to the admin dashboard that verifies if that variable is set to check if it is really an admin that came on the page.
As explained in the title, the main problem is that a session is indeed created as i test the main page, but when i click on the link to the log in form, the session seems to be destroyed despite the fact that i erased or neutralized any possible instructions that would results in doing so.
The small php snippet on the main page starting the session (main.php)
<?php
session_start(['cookie_lifetime' => 86400]);
$_SESSION["start"] = time();
error_log("Test de session : ".session_status()." | ".$_SESSION["start"]."; \n", 3, "log1.txt"); //puts in the log the session status and the content of the variable assigned above.
if (!is_writable(session_save_path())) {
error_log('Session path '.session_save_path()." is not writable for PHP; \n", 3, "log1.txt");
} else {
error_log('Session path '.session_save_path()." is writable for PHP; \n", 3, "log1.txt");
}
?>
I've tried overriding the cookie lifetime and as shown above took the snippet of this question's answer to see if the folder was writable and the session was created.
The logs always return on the main page :
Test de session : 2 | 1684946314;
Session path C:\MAMP\bin\php\sessions\ is writable for PHP;
(the number after the | in the first line being the expected timestamp).
The only php snippet in the log-in form (connexion.php)
<?php
if (isset($_SESSION["logged_admin"])) {
header("Location: auth.php");
exit();
}
error_log("Test de session : ".session_status()." | ".$_SESSION["start"]."; \n", 3, "log1.txt");
if (!is_writable(session_save_path())) {
error_log('Session path '.session_save_path()." is not writable for PHP; \n", 3, "log1.txt");
} else {
error_log('Session path '.session_save_path()." is writable for PHP; \n", 3, "log1.txt");
}
?>
I've put the first if up there to redirect directly a logged-in admin to the dashboard if they were already connected. The lines after are doing the same tests as in main.php, but this times returns in the logs :
Test de session : 1 | ;
Session path C:\MAMP\bin\php\sessions\ is writable for PHP;
Which suggests the session was destroyed and all its variables unset.
Parts of the code in the php file responsible of checking the username and passwords provided related to the use of sessions (auth.php)
<?php
error_log("\n\n------- [AUTH START ".date(DATE_RFC2822)." ] -------\n", 3, "log1.txt");
$fail = 0;
/*if (isset($_SESSION["logged_admin"]) && isset($_SESSION['start']) && (time() - $_SESSION['start'] > 1800)) {
session_unset();
session_destroy();
session_start(['cookie_lifetime' => 86400]);
$_SESSION["start"] = time();
error_log("Session expirée (connecté + de 30 min);\n", 3, "log1.txt");
echo "Votre session a expirée. Veuillez vous reconnecter.";
$fail = 1;
goto fail;
}*/ //code that checks if a session is loaded during too much time and if yes, destroys it. I've put the code in a comment so it normally shouldn't be executed by the server.
error_log("Test de session : ".session_status()." | ".$_SESSION["start"]."; \n", 3, "log1.txt");
if (!is_writable(session_save_path())) {
error_log('Session path '.session_save_path()." is not writable for PHP; \n", 3, "log1.txt");
} else {
error_log('Session path '.session_save_path()." is writable for PHP; \n", 3, "log1.txt");
} //Here's once again the similar tests done in the other files.
if (isset($_SESSION["logged_admin"])) {
error_log("L'administrateur est déjà connecté;\n", 3, "log1.txt");
goto fail;
}
//Other stuff that verifies if the data sent with POST method is there and connecting the local server to the database i use.
$Accounts = $AccountsQuery->fetchAll(); //Converts the data i've received via a SQL query
foreach ($Accounts as $Compte) {
if ($Compte["login"] == $login && $Compte["mdp"] == $mdp) {
$_SESSION["logged_admin"] = $login; //if a username-password couple from the registered admins corresponds to the couple sent via the log in form, the username retrieved from the log in form ($login) is associated to the session's array.
error_log(session_status()."; \n", 3, "log1.txt");
error_log("Login et mot de passe valides | ".var_dump($_SESSION["logged_admin"])." est désormais connecté sur la session ".session_id()." ;\n", 3, "log1.txt");
goto fail;
}
}
$fail = 1;
error_log("Login et mot de passe invalide; \n", 3, "log1.txt");
echo "L'identifiant ou le mot de passe fourni est invalide."; ?>
The logs returned by the execution of the file, after submitting the form :
------- [AUTH START Wed, 24 May 2023 16:49:17 +0000 ] -------
Test de session : 1 | ;
Session path C:\MAMP\bin\php\sessions\ is writable for PHP;
PDO set up for authentification;
1;
Login et mot de passe valides | est désormais connecté sur la session ;
Authentification réussie le Wed, 24 May 2023 16:49:17 +0000 - British GMT hour ----------------------- [AUTH END]
As i've put registered admin credentials in the form, the authentification itself succeeds but the session created in the main page is proven to be still deleted after clicking to access the log in form, therefore rendering impossible putting the username of the logged-in admin in the $_SESSION array.
The if structure preventing unauthorized users from accessing admin-only dashboard content (dashboard.php)
<?php if (isset($_SESSION["logged_admin"])) { ?>
//If there's a logged-in admin, shows up the dashboard with the admin-stuff to do.
<?php
} else {
echo "Vous ne pouvez pas accéder à cette page car vous n'êtes pas connecté. Veuillez vous rediriger vers la page principale.";
};
?> //Else shows the user on the page that he isn't logged-in.
Extracts of the two configuration files of the PHP component used in my server (php 8.1.0)
php.ini-development
...
;
; where MODE is the octal representation of the mode. Note that this
; does not overwrite the process's umask.
; https://php.net/session.save-path
session.save_path = "tmp/"
php.ini-production
;
; where MODE is the octal representation of the mode. Note that this
; does not overwrite the process's umask.
; https://php.net/session.save-path
session.save_path = "tmp/"
The session.save_path parameter is clearly uncommented in both. However, it isn't the path returned by the session_save_path() function.
答案1
得分: 1
每当你加载一个新页面时,都会发起一个不同的HTTP请求。会话必须在每个HTTP请求中启动,因此,你必须在每个页面中添加 session_start()
。
我建议创建一个单独的头文件,将其包含在所有页面中,这样可以设置其他在所有页面中都需要的东西,比如如果用户未登录则重定向到登录界面。
英文:
https://www.php.net/manual/en/function.session-start.php
Every time you load a new page, it's a different HTTP request. The session must be started on every HTTP request, therefore, you must add session_start()
to every page.
I recommend creating a single header file that gets included in all of your pages, it can be useful to set up other things that are required on all pages too, such as redirecting to a login screen if the user is not logged in.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论