In my index.php I am including checkUser.php with the following code:
<?php
session_start();
echo("DEBUG_checkUser:" . $_SESSION['name'] . "<br>");
if (!isset($_SESSION['name'])) {
header('Location: denied.php');
} else {
echo("<span style='font-size: 12px'>Logged in as " . $_SESSION['fname'] . " " . $_SESSION['lname'] . " (" . $_SESSION['name'] . "). ");
echo("<a href='../POC/logoff.php'>Logoff</a>.");
echo("</span>");
}
?>
Then I have logoff.php with the following code:
<?php
session_start();
unset($_SESSION['name']);
//echo("DEBUG" . $_SESSION['name'] . "<br>"); //Notice: Undefined index: name in D:\XAMPP\htdocs\POC\logoff.php on line 5
session_unset();
session_destroy();
header('Location: ../POC/index.php');
?>
My expectation is, that by clicking Logoff, $_SESSION['name'] will be unset, and the user will be redirected from index.php to denied.php. This works as expected in Chrome (103.0.5060.114), but not in Firefox (103.0b9).
Functions session_unset() and session_destroy() are redundant IMO (indeed in Chrome it works without), I just added them to avoid getting answers, that I should add them.
If I comment out redirection to index.php and uncomment the display of $_SESSION['name'], I get an error for undefined index, so the session variable is correctly unset, but why Firefox does not accept that after redirection to index.php? And $_SESSION['name'], even though correctly unset in logoff.php, displays existing name, as the unsetting were not taking place.
I deleted all cookies for 'localhost' which I am using.
Cookie PHPSESSID is the same before and after logoff.
What should I do so this would also work in Firefox?
EDIT:
It was a cache issue, I set this to 0 seconds in .htaccess file and now everything works in both browsers:
<FilesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=0, private, proxy-revalidate"
</FilesMatch>
So the question would be ... why did this work in Chrome before, when the cache for php was set to 60 seconds?
It makes no difference what browser you are using, the session is server-side. I think this is a browser cache situation. Open the Developer Tools in Firefox and disable the cache on the Network tab (see where).
Related
PHP 7.1.7 on Windows Server 2008 Enterprise
... I noticed there were 5 other questions here just like this with no answer. I'm getting frustrated trying to do something that's always been so easy to accomplish in other languages for me. I just want to set a session variable and then read it on another page after a redirect. That should be simple basic functionality and I do not get why I've been sitting here for 2 hours trying everything I can think of and I still can't figure it out.
Each page of my application starts with: session_start();
I have a form edit processing page I'm starting with, where on a successful edit, the user is redirected back to the index page. Before the redirect, I'm setting a session variable ('success'). At this point, the session variable is set. If I comment out the header and exit() lines and echo the session["success"] variable.
$_SESSION["success"] = "The record was inserted successfully.";
header( 'Location: index.php');
exit();
}
Register Globals does not exist in my PHP.ini file (register_globals). I tried adding "register_globals=0;" to the PHP.ini file and restarting the server but I still doid not see a "register_globals" listing on the PHP info page.
No matter what I have tried, after the redirect to the index.php page, that session variable does not exist after the redirect ($_SESSION["success"]). I'm staying inside the same domain (same folder on the server really)
After setting the session variable ('success') and proving that it is set by echoing it on the edit proccessing page followed by an exit, I can not figure out how to get the session variable to persist after a redirect or page change:
If I try and echo that 'success' session variable after a redirect, I get this:
Notice: Undefined index: success
I'm not understanding why this is so difficult? What else could I try?
Thanks for any help.
Test whether the session cookie is set properly.
$_SESSION["success"] = "The record was inserted successfully.";
// header( 'Location: index.php');
echo session_name() .': '.session_id(); // print session cookie name & value
echo '<pre>' . print_r(session_get_cookie_params() ) . '</pre>';
exit();
What do you see? Open your browser's dev tools and look at cookies set when the server echoes the info above. If there is no cookie with the name (typically PHPSESSID) and session ID value above, then either your browser is not accepting cookies or the server isn't setting them. Either one will break cookie-based sessions.
If these seem to work ok, then re-establish your redirect. On the next page (index.php in your example), take a look at which cookies are received:
// Notice: this won't work on the page setting the cookie.
// Cookie should show up on the next page
echo '<pre>' . print_r($_COOKIE) . '</pre>';
Does the session id cookie exist?
If all this works, I would then look at whether PHP is actually storing session files properly. Session data is serialized and saved to files in a folder on the server's hard drive. Take a look at your php.ini, where you should see something like:
session.save_handler = files
session.use_cookies = 1
; where on server the files should be stored. the folder should be
; readable/writeable to the PHP process. Maybe '/tmp'?
session.save_path =
If you edit your php.ini, remember to restart the server.
Update
From your comments, everything seems to be setup correctly. Remove all other code. and just have this:
page1.php
<?php
session_start();
$_SESSION = []; //start with an empty array
$_SESSION['success']= 'record saved';
$_SESSION['id'] = session_id();
header('Location: index.php');
exit;
index.php
<?php
session_start();
var_dump($_SESSION);
if(isset($_SESSION, $_SESSION['id'])):
echo 'Session ids ' . ($_SESSION['id']===session_id()? 'match' : 'do not match');
endif;
What gets var-dumped in index.php after you get redirected from page1.php?
I have a rather strange problem; there are three pages which are using this cookie - one sets $_SESSION = 0 (as another Stack article suggested my issue might be related to PHP having difficulties with timings so 'pre-creating' the session, then writing to it might help), another file starts the session, changes the session cookie to an array with some useful data in it and supposedly saves it. Only, in this file the session will never actually get written to disk... On the third page, I will try and access the cookie and get an output of '0' (first page).
I've spent a lot of time debugging this and have checked:
That session_start and session_write_close are being used appropriately.
That PHP.ini is set up correctly, with a writable storage path (/tmp)
That PHP is actually using this storage path!
And I've also sat there comparing cookie ID's in browser and on the server to work out when sessions are and are not being created.
I don't see an issue in my code, and as other pages are able to use the session correctly (pages 1 and 3), it is only page 2 which is having an issue.
This is my debugging output from page two, showing the array I tried to write plus the fact that PHP doesn't seem to know what the session ID is, but there are no errors when I call session_start?
bool(true)
session id:
session file: /tmp/sess_ does not existarray(3) {
["user"]=>
string(5) "kevin"
["time"]=>
int(1472646292)
["ip"]=>
string(13) "178.62.20.247"
}
array(1) {
["oscar"]=>
string(26) "9h8c8fgkscitc7l3m7t18f37u2"
}
And the pertinant code from page two:
<?php
//error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//session starts
session_name("oscar");
var_dump(session_start());
session_regenerate_id();
if (! is_writable(session_save_path())) { throw new \Exception( session_save_path() . ' NOT WRITABLE!'); }
$_SESSION['user'] = $_POST['username'];
$_SESSION['time'] = time();
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
echo '<pre>';
echo 'session id: ', session_id(), "\n";
$sessionfile = ini_get('session.save_path') . '/' . 'sess_'.session_id();
echo 'session file: ', $sessionfile, ' ';
if ( file_exists($sessionfile) ) {
echo 'size: ', filesize($sessionfile), "\n";
echo '# ', file_get_contents($sessionfile), ' #';
}
else {
echo ' does not exist';
}
var_dump($_SESSION);
var_dump($_COOKIE);
echo "</pre>\n";
session_write_close();
exit();
?>
The output of var_dump(session_start()); is
bool(true)
And if you refresh the page, the output of $_COOKIE changes (as the session ID is changed).
Thank you for any help - I hope I'm not being stupid. I've made a lot of effort debugging this.
EDIT:
This now appears to be an issue with where scripts are in the filesystem.
All the files are loaded through one index.php - the ones that don't update sessions (don't work) are located in api/filename.php, whilst, ones that do work are located in ../server/includes/admin/filename.php. (Nb. those paths are relative to index.php)
System: Ubuntu Server 16.04 PHP7 Apache2
Many thanks to Ryan Vincent who helped solve this over chat.
It stems from the way the actual scripts were loaded - using relative paths from a file higher up the directory. Unfortunately, this caused PHP some issues but didn't generate any errors. By transitioning to absolute paths: DIR . api/filename.php we managed to fix the problem.
session_start();
Should be at the top of the script and it should be on top of every page where session variables are used if the included files on top does not contain session_start().
Hi Today I am facing one strange Problem
After login validation I am storing the user name in session and redirecting it to some other page .
Validation page .
if (mysql_num_rows($sqlQuery) == 1) {
session_start();
$_SESSION['username'] = $login;
print $_SESSION['username'];
header("Location: dialout.php");
}
.
on dialout.php I am trying to print session like
var_dump($_SESSION);
But it doesn't print anything .
some googling I found that problem might be in writing the session directory .
So to check that I wrote one script .
print session_save_path();
if (!is_writable(session_save_path())) {
echo 'Session path "'.session_save_path().'" is not writable for PHP!';
}
else{
echo "writable -------------";
}
From above script I am getting writable.
Just wondering why my I am unable to access the session on dialout.php page
In your Validation page,the following code should be at the top of the file, as first line in your code.
session_start();
It should be included in every page if you want to use session variable.
First, carry out these usual checks:
Make sure session_start(); is called before any sessions are being
called. So a safe bet would be to put it at the beginning of your
page, immediately after the opening
After the header redirect, end the current script using exit();
(Others have also suggested session_write_close(); and
session_regenerate_id(true), you can try those as well, but I'd use
exit();)
Make sure cookies are enabled in the browser you are using to test
it on.
Ensure register_globals is off, you can check this on the php.ini
file and also using phpinfo(). Refer to this as to how to
turn it off.
Make sure you didn't delete or empty the session
Make sure the key in your $_SESSION superglobal array is not
overwritten anywhere
Make sure you redirect to the same domain. So redirecting from a
www.yourdomain.com to yourdomain.com doesn't carry the session
forward.
Make sure your file extension is .php (it happens!)
can all be found here: PHP session lost after redirect
Call session_start function in dialout.php befor accessing session variable like this :
session_start();
var_dump($_SESSION);
So I have a problem where I have several $_SESSION values defined and need to be sent to the next page. Here is a quick look at the meat of my problem.
login.php
session_set_cookie_params(900, '/', 'localhost:8080/test/');
session_start();
$_SESSION['first_name'] = "Moe";
$_SESSION['last_name'] = "Joe";
header("Location: http://" . $_SERVER['HTTP_HOST'] . "/test/admin_console.php?" . SID);
exit();
?>
On the next page, I expect my $_SESSION['first_name'] and $_SESSION['last_name'] to be defined as they have been set by the code above. The following is the meat of my code in the next page
admin_console.php
session_name('AdminLogin');
session_start();
#Set page title and include HTML header
$page_title = 'Administrative Console';
include('./header.inc');
$mysession = session_get_cookie_params();
$msg = $_SESSION['first_name'];
echo "Is the thing set? " . $msg . "<br />";
?>
The problem is, i get the following error:
*Notice: Undefined index: first_name in C:\wamp\www\test\admin_console.php on line xx*
I can't for the life of me figure out why $_SESSION['first_name'] wont retain its value from previous page. i have session_start() in every page and i even went as far as to add several lines to completely kill the session at the end of this page
<?php
$_SESSION = array();
session_destroy();
setcookie('PHPSESSID', '', time()-300, '/', '', 0);
?>
So my echo statement should display the value that is entered in $_SESSION, but to no avail. Any help?
OH MY GOD, it is the worst mistake in the world.
Google Chrome, for some reason, saves previous attempts or pages. So during my initial tests, the page failed. But when I fixed the code, the browser still retained the old style.
I just now had this feeling in my gut to try the code in the Incognito mode, and it WORKED!
Lesson Learned: If your code looks perfect and you're still getting same error no matter what, try a different browser or clear out browser cache.
It's just a notice (warning). You can set error_reporting(7); to get rid of this message.
Your code looks fine , check your php info "session section".
I narrowed the problem down to this statement.
if (!setcookie("cookielogin",$usernametocheck, time()+3600)) echo "cookie setup failed<br/>";
Every time I run the code it shows "cookie setup failed" on browser.
I checked the browser for cookies stored by the site and I don't see my cookie.
Can anybody help ?
add ob_start(); at the top of your page and ob_clean() after setting cookie .
<?php
ob_start();
#Code..........
#Code...........
#Code............
if (!setcookie("cookielogin",$usernametocheck, time()+3600)) echo "cookie setup failed<br/>";
ob_clean();
#code......
?>