PHP Session variables resetting with each page load - php

My session variables are resetting every time I load a new page.
I have included a header.php file to each script with the session_start() function at the very top like so:
session_start();
error_reporting(E_ERROR);
I have also checked to make sure that the session_id is the same across all pages and it is.
I checked my web host's php_ini config file and I saw that the session.save_path was set to /tmp. I changed it to /var/lib/session/ like someone had suggested on this site and I began to get odd warnings in my code.
Warning: session_start() [function.session-start]: open(/var/lib/php/session//sess_97fca6d21c7ffa8333cd42eaa87f2eac, O_RDWR) failed: Permission denied (13) in /home/mforsyth/public_html/Beesting/header.php on line 2
I do not know what to do to fix this problem. Any help would be useful. If more details are needed please let me know.
EDIT: I have changed the folder back to /tmp and have made sure i can read/write into it and I can. I have also echoed the session id on every page and it all comes out the same. Also it seems that the session only lasts for one page

What happens is that php tries to track your sessions with some information it writes to the directory that ThinkingMonkey mentioned.
As the directory is not writable by the php/webserver process' user, this fails. Thus you don't get a session.
Find out which user the process is running under and grant him the read/write right for that directory.

Thanks for the help. After further investigation and talking to my host about the matter, I was able to find conclude that the problem was NOT the capability of writing to the /tmp folder. In fact what the problem really was, was a javascript function in my header.php include file.
function logout()
{
<?
session_destroy();
?>
alert("you have been logged out");
}
It was avoiding the fact that it was in a function, probably my fault seeing how the two languages are compiled differently. I did a simple ajax call to take care of the session destroy and all is well now. I wonder if anyone else out there has similar problem and if this helps them.

Try restarting the webserver and php service, in case of nginx/php-fpm, try
root#server > service nginx restart
root#server > service php-fpm restart
that should do the trick!

Had the same general problem and it turns out for some reason I was using JavaScript to delete the session cookie.
document.cookie = '[session_name]' +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';

Related

Can't write PHP cookies or sessions on RackSpace server

I'm working on a RackSpace server, and I am unable to successfully write cookies or persistent sessions through PHP (I can write javascript cookies just fine).
The cookies are never written at all, and the sessions are never accessible on any page but the one they're written on. I've tried the exact same code on a different server, and it worked just fine -- so I'm assuming it's some kind of configuration issue.
Here's an example:
Sessions
Page 1:
session_start();
$_SESSION['mysession'] = 'hello';
//writes correct value
echo $_SESSION['mysession'];
Page 2:
session_start();
//this dumps 'NULL'
var_dump($_SESSION['mysession']);
Cookies:
//this never gets written.
setcookie($mycookie, $myvalue, time() + (86400 * 30), "/");
Are there any particular server settings I should be looking at?
I ran phpinfo, and see my session.save_path. I tried setting that to 777 just to see if it would help, but it did not.
I'm stumped, and their support couldn't help me. Anyone have any ideas?
Edit:
Upon closer inspection, I can see that the sessions are being written -- I just can't read them.
You can gather more information by creating a php file with content:
<?php phpinfo();
Request this site and search for the session settings.
- Are sessions really enabled?
- Which session save handler is used?
Maybe the session data is not even saved in a file and the error is anywhere else.

Cannot start session without errors in phpMyAdmin, session variables don't work

First, I have already looked at rciiipo's post from 2011. My problem don't seem to be fixed with the answers provided, and I have a few other inputs.
I get the below error when pointing browser to phpMyAdmin
Cannot start session without errors, please check errors given in
your PHP and/or webserver log file and configure your PHP installation properly.
Also ensure that cookies are enabled in your browser.
1) Session variables don't work with any php file. I am little unsure if it is related, but i believe the one problem causes the other.
This code below should display "teddy" when i refresh the webpage:
<?php
session_start();
$username = $_SESSION['username'];
if(isset($_SESSION['logged']) && $_SESSION['logged']=='yes') {
echo "$username";
}
$_SESSION['username']='Teddy';
$_SESSION['logged']='yes';
?>
My php.ini file:
session.save_path = "/var/lib/php5/session"
Permissions:
drwxr-xr-t 4 root www-data 4096 Sep 1 08:40 php5
|
-- drwxr-xr-x 2 root www-data 4096 Sep 1 08:40 session
I think the problem can be fixed if I only get $_SESSION variables to work in php.
I agree with bansi:
it looks like you have wrong permission for /var/lib/php5/session it
should be drwxrwxr-t or dr-xrwxr-t (assuming www-data is the web
server user). Write permission is required in the directory to save
session data.
Also, you should check the log files in /var/log/ of PHP (and maybe Apache as well) - they might give you some more details...

PHP resetting Session after some time

I know this problem has been presented here in SO and I've tried the solutions but it's still not fixed.
PHP is deleting the session after some time of inactivity (i assume 24 minutes as it's the default and seems to fit the testing).
I have the following code set in all the pages:
ini_set('display_errors', 0);
$sessionCookieExpireTime = 2880000;
session_set_cookie_params($sessionCookieExpireTime);
ini_set('session.gc_maxlifetime', $sessionCookieExpireTime);
session_start();
echo ini_get('session.gc_maxlifetime'); //echos 2880000 as expected
But the session still gets reset after 24 minutes (or so) of inactivity.
phpinfo() return the following output for session:
Any idea why this isn't working? (PHP 5.3.10)
Thanks
Although Marc B answer shares some great insight it wasn't working for me. I was pretty sure everything was fine with my script and I had nothing messing with the session in my code.
After an epic struggle I discovered that my problem was actually due to shared hosting environment. From the PHP doc:
“If different scripts … share the same place for storing the session
data then the script with the minimum value will [determine the
session timeout]“.
After this the problem was quite obvious. Some script (hosted on the same server) was using the default php.ini session.gc_maxlifetime and that was resetting my sessions.
The solution was to create a folder under the root of my hosting (make sure it's not web accessible), set the right permissions to it and then use session.save_path to tell php where to store my sessions. Something like:
ini_set("session.gc_maxlifetime","21600"); // 6 hours
ini_set("session.save_path", "/your_home/your_sessions/");
session_start();
This website provided great insight: php sessions on shared hosting
So if you come accross this issue make sure you follow Marc B recommendations and if that doesn't work try this out.
Best wishes!!
Are you doing this code in EVERY script that uses sessions? ini_set changes apply ONLY to the script they're executed in, and ONLY for the execution lifetime of that particular script.
If you want to make it a permanent global change, you'll have to modify php.ini, or put some php_values directives into http.conf/.htaccess.

phpsessid in cookie over https

in my local WAMP server, when I call session_start() the session-id is being set in the cookie as follows and var_dump($_COOKIE) gives the following.
array
'PHPSESSID' => string 'qg8nrlpdtgb391386lhghgv727' (length=26)
so when I call session_start() again, my previous session is resumed.
but when I deployed the same code to my web-server, the PHPSESSID is not being set in the cookie. So as a result, every time I call session_start(), a new session is getting created instead of resume the previous session.
Can anyone please tell me a possible cause of the problem. Do we have to explicitly set the PHPSESSID to the cookie?
Also, In my local(WAMP) I dont have https, but the web-server where I pushed the code is https. Is this a problem?
I am stuck with this for almost 3 days now.
Thanks in advance.
Kanna
Looks like session handling is configured differently on this webserver. You should compare the values set in the php.ini file under the session-section.
Especially:
Is session.use_cookies set to 1?
Does session.save_path point to a valid directory, where the webserver user has write permission
See here for a full list of session-settings:
http://de3.php.net/manual/de/session.configuration.php
I had called session_start() immediately after html < head > tag. This was the problem. When I moved the session_start() method before the html head tag, the problem was solved.
Thanks everyone for your help.
Kanna

session_start hangs

since a few hours our server hangs every time you do a session_start.
For testing purposes i created a script which looks like this:
<?php
session_start();
?>
Calling it from the console hangs and it can't even be stopped with ctrl-c, only kill -9 works. The same for calling it via Apache. /var/lib/php/session/ stays empty but permissions are absolutely fine, www can write and also has read permissions for all parent folders.
According to the admins there were no changes made on the server and there is no special code registered for sessions. The Server is CentOS 4 or 5 and yesterday everything was working perfectly. We rebooted the server and updated PHP, but nothing changed.
I've ran out of ideas, any suggestions?
UPDATE
We solved this problem by moving the project to another server, so while the problem still exists on one server there is no immediate need for a solution anymore.
I will keep the question open in case someone has an idea for others having a similar problem in the future, though.
There are many reasons for that, here are a few of them:
A. The session file could be opened exclusively.
When the file lock is not released properly for whatever reason, it is causing session_start() to hang infinitely on any future script executions.
Workaround: use session_set_save_handler() and make sure the write function uses fopen($file, 'w') instead of fopen($file, 'x')
B. Never use the following in your php.ini file (entropie file to "/dev/random"), this will cause your session_start() to hang:
<?php
ini_set("session.entropy_file", "/dev/random");
ini_set("session.entropy_length", "512");
?>
C.
session_start() needs a directory to write to.
You can get Apache plus PHP running in a normal user account. Apache will then of course have to listen to an other port than 80 (for instance, 8080).
Be sure to do the following things:
- create a temporary directory PREFIX/tmp
- put php.ini in PREFIX/lib
- edit php.ini and set session.save_path to the directory you just created
Otherwise, your scripts will seem to 'hang' on session_start().
If this helps:
In my scenario, session_start() was hanging at the same time I was using the XDebug debugger within PHPStorm, the IDE, on Windows. I found that there was a clear cause: Whenever I killed the debug session from within PHPStorm, the next time I tried to run a debug session, session_start() would hang.
The solution, if this is your scenario, is to make sure to restart Apache every time you kill an XDebug session within your IDE.
I had a weird issue with this myself.
I am using CentOS 5.5x64, PHP 5.2.10-1. A clean ANSI file in the root with nothing other than session_start() was hanging. The session was being written to disk and no errors were being thrown. It just hung.
I tried everything suggested by Thariama, and checked PHP compile settings etc.
My Fix:
yum reinstall php; /etc/init.d/httpd restart
Hope this helps someone.
To everyone complaining about the 30 seconds of downtime being unacceptable, this was an inexplicable issue on a brand new, clean OS install, NOT a running production machine. This solution should NOT be used in a production environment.
Ok I face the same problem on 2 PC, 1 is MAC mini XAMPP, 1 is Windows 10 Xampp.
Both is php spent infinity to run session_start(). Both PHP version is 7.x.x
I found that session files is lock to read and write. So that I added code to make PHP read session files and immediately unlock when done with
<?php
session_start([
'read_and_close' => true,
]);
?>
or
<?php
//For PHP 5.x
session_start();
session_write_close();
?>
After this PHP unlock session file => Problems solve
The problem: -
Iv experienced (and fixed) the problem where file based sessions hang the request, and database based sessions get out of sync by storing out of date session data (like storing each session save in the wrong order).
This is caused by any subsequent request that loads a session (simultaneous requests), like ajax, video embed where the video file is delivered via php script, dynamic resource file (like script or css) delivered via php script, etc.
In file based sessions file locking prevents session writing thus causing a deadlock between the simultaneous request threads.
In database based session the last request thread to complete becomes the most recent save, so for example a video delivery script will complete long after the page request and overwrite the since updated session with old session data.
The fix: -
If your ajax or resource delivery script doesnt need to use sessions then easiest to just remove session usage from it.
Otherwise you'd best make yourself a coffee and do the following: -
Write or employ a session handler (if not already doing so) as per http://www.php.net//manual/en/class.sessionhandler.php (many other examples available via google search).
In your session handler function write() prepend the code ...
// processes may declare their session as read only ...
if(!empty($_SESSION['no_session_write'])) {
unset($_SESSION['no_session_write']);
return true;
}
In your ajax or resource delivery php script add the code (after the session is started) ...
$_SESSION['no_session_write'] = true;
I realise this seems like a lot of stuffing around for what should be a tiny fix, but unfortunately if you need to have simultaneous requests each loading a session then it is required.
NOTE if your ajax or resource delivery script does actually need to write/save data, then you need to do it somewhere other than in the session, like database.
Just put session_write_close(); befor Session_start();
as below:
<?php
session_write_close();
session_start();
.....
?>
I don't know why, but changing this value in /etc/php/7.4/apache2/php.ini worked for me:
;session.save_path = "/var/lib/php/sessions"
session.save_path = "/tmp"
To throw another answer into the mix for those going bananas, I had a session_start() dying only in particular cases and scripts. The reason my session was dying was ultimately because I was storing a lot of data in them after a particularly intensive script, and ultimately the call to session_start() was exhausting the 'memory_limit' setting in php.ini.
After increasing 'memory_limit', those session_start() calls no longer killed my script.
For me, the problem seemed to originate from SeLinux. The needed command was chcon -R -t httpd_sys_content_t [www directory] to give access to the right directory.
See https://askubuntu.com/questions/451922/apache-access-denied-because-search-permissions-are-missing
If you use pgAdmin 4 this can happen as well.
If you have File > Preferences > SQL Editor > Options > "Auto Commit" disabled, and you just ran a query using the query tool but didn't manually commit, then session_start() will freeze.
Enable auto commit, or manually commit, or just close pgAdmin, and it will no longer freeze.
In my case it seems like it was the NFS Share that was locking the session , after restarting the NFS server and only enabled 1 node of web clients the sessions worked normally .
Yet another few cents that might help someone. In my case I was storing in $_SESSION complex data with several different class objects in them and session_start() couldn't handle the whole unserialization as not every class was loaded on session_start. The solution is my case was to serialize/jsonify data before saving it into the $_SESSION and reversing the process after I got the data out of session.

Categories