My PHP sessions are being created but $_SESSION variables are not being written to the session file.
I have three test PHP pages here that I'm using to diagnose this problem:
test_a.html:
<html>
<body>
<form action='test_b.php' method='post'>
Put something here:
<input type='text' name='saveme' />
<input type='submit' value='Go!' />
</form>
</body>
</html>
test_b.php:
<?php
session_start();
$_SESSION['saveme']=$_POST['saveme'];
echo "Here's what you wrote:<br>".$_SESSION['saveme']."<br>".
"<a href='test_c.php'>Take me to the final check</a><br>";
echo "And here's your session_id: ".session_id();
session_write_close();
?>
test_c.php:
<?php
session_start();
echo "Here's what you wrote (maybe?):<br>".$_SESSION['saveme']."<br>".
"You should also see saveme below:<br>";
foreach ($_SESSION as $key=>$val)
echo $key." ".$val."<br>";
echo "And here's your session_id: ".session_id();
?>
When opening test_a.html and typing in anything to the textbox and hitting Go!, it will show up correctly on test_b.php (when it is set and recalled from memory) but it is not shown on test_c.php.
The session_id is set and shows to be the same. The cookie is stored correctly. The session file is created correctly in the filesystem, but is not written to and remains a zero-byte file.
Sessions are now not being written on any pages of my site (despite working for well over a year up to this point) so typos in these code snippets (if any) are likely irrelevant.
Things I've checked:
The session storage directory is writeable and the disk has plenty of storage
session_start is always successful (and there is nothing before it)
The session_id is created correctly and is the same on both pages
The session cookie is created with the correct session_id
session.use_cookies and session.use_only_cookies are on
Register globals is off
Cookies are enabled
Cleared the /tmp directory to reduce possibility of filesystem issues
Tried storing the session data in memory (didn't work)
Tried changing the session file location (didn't work)
Tested on Chrome & Firefox
Ideas?
Your session storage directory may be writable but the file is not. Try setting the rights to 0666 on the session file and check if this fixes the problem. It's something like one process is creating the file and the very next is not able to write it. What's the owner of the file at creation time? Check if it's www-data or whatever runs your php.
PHP session keys are separated by the pipe character | so | in key name will break you session. Maybe this is the problem.
Check this:
enter link description here
Related
I have created a very basic script to test $_SESSION parameters, and on my server this works perfectly:
<?php
session_start();
if(!isset($_SESSION["favcolor"]))
{
$_SESSION["favcolor"] = "green";
}
?>
<html>
<head>
</head>
<body>
<?php
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
?>
<br /><br />
Go To Next Page
<br />
Delete Session
</body>
</html>
Page 2 is the exact same, only using a second Session variable, and the kill link does a session_unset() and a session_destroy(), then redirects to test1.php. Again, on my server this code works perfectly.
However, the exact same code (simply copied and pasted without any changes) on the server of my client does not work. Between test.php and test2.php the session variable set in test1.php gets lost. Similarly, going back, the variable set in page 2 is getting lost.
I have been looking at the phpinfo() stuff to see if I see clear differences, but I am at a loss here...
This can be caused by a lot of things, but just to start troubleshooting:
This function returns True or False, depending if it could start the session or not, so maybe you can print this returned value, to check wether it is actually saving the value for you or not.
If not, you surely ran into a php.ini configuration issue and you'll have to check these values on your client's server.
You can check the documentation for session_start() at php's official site
This was due to a mis-configured session.save_path.
After pointing it to a proper folder, things are working properly
I have cpanel based centos server.
I am facing issue of session variable not available through out the pages.
I checked all server setting but unable to get idea what i missed out.
<?php
session_start();
// index.php
echo "session id = " .session_id();
$_SESSION["username"] = "Niraj";
echo '<br />Lets see if session available in page 2 -> page 2';
if (!is_writable(session_save_path())) {
echo '<br><br><br><br>Session path "'.session_save_path().'" is not writable for PHP!';
}
else
{
echo '<br><br><br><br>Session path "'.session_save_path().'" is writable for PHP!';
}
?>
Output of above index.php as under:
session id = 5f59e48f328ef72fda877c8a9f7a07ca
Lets see if session available in page 2 -> page 2
Session path "/var/tmp" is writable for PHP!
If i refresh page, than session id remain same.
Code of page2.php as under:
<?php
session_start();
//page2.php
echo "session id = " .session_id();
echo "<br> Username = " . $_SESSION["username"];
?>
Output of page2.php as under:
session id =d99088ca0027a483301746e02282662c
Username =
Problem is Username doesn't output any session value. Temporary directory is writable and browser support cookies.
I marked that when click on page2.php, it will shows new value in session id, is it okay or session id should remain same across all pages?
I tried everything and put lots of effords since last 2 days,
same code working fine with other windows server and session id remain same until i close browser.
Thanks
session_id() must remain the same for you to query data which was set to that session id. The session id (dependent on lifetime value) will stay with you until the browser closes. I suspect that your browser is blocking session cookies which is causing PHP to regenerate a new ID each time the page loads. Download a new browser which you havent used before and test the theory and let me know how you get on.
You can check the global session cookie values and see what the lifetime is set to if you wish but I bet its the browser (0 == Lifetime -> until browser closes).
var_dump(session_get_cookie_params());
http://php.net/manual/en/function.session-get-cookie-params.php
Also....
You could just disable any plugins you have especially ones which stop ad's like Adblocker etc...
Have you seen anything strange occurring to the session files in /var/tmp? Could the server be deleting them?
MediaTemple Grid servers seem to have issues with sessions when they save to the tmp folder. I understand you may not be using MediaTemple, but their DV servers run CentOS so it could have something to do with the OS.
https://mediatemple.net/community/products/grid/204643480/why-am-i-experiencing-session-errors
The symptom of interest they list is "General problems with sessions not seeming to be carried across web requests." Their solution is to get session files out of the tmp folder and store them somewhere else by setting session.save_path in php.ini and restarting apache.
Here are the code of my login page where the login script checks for the authenticity of the user and then redirects to inbox page using header function.
<?php
session_start();
include_once('config.php');
$user=htmlentities(stripslashes($_POST['username']));
$password=htmlentities(stripslashes($_POST['password']));
// Some query processing on database
if(($id_user_fetched<=$id_max_fetched) && ($id_user_fetched!=0)){
$_SESSION['loggedIn'] = 'yes';
header("Location:http://xyz/inbox.php?u=$id_user_fetched");
//echo 'Login Successful';
}else{
echo 'Invalid Login';
echo'<br /> Click here to try again';
}
}else{
echo mysqli_error("Login Credentials Incorrect!");
}
?>
The inbox.php page looks like this:
<?php
session_start();
echo 'SESSION ='.$_SESSION['loggedIn'];
if($_SESSION['loggedIn'] != 'yes'){
echo $message = 'you must log in to see this page.';
//header('location:login.php');
}
//REST OF THE CODE
?>
Now with the above code, the inbox.php always shows the output:
SESSION=you must log in to see this page.
Which means that either the session variable is not being setup or the inbox.php is unable to retrieve the session variable. Where am i going wrong?
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 <?php tag before anything else. Also ensure there are no whitespaces/tabs before the opening <?php tag.
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!).
PHP session lost after redirect
I had the same issue for a while and had a very hard time figuring it out. My problem was that I had the site working for a while with the sessions working right, and then all of the sudden everything broke.
Apparently, your session_save_path(), for me it was /var/lib/php5/, needs to have correct permissions (the user running php, eg www-data needs write access to the directory). I accidentally changed it, breaking sessions completely.
Run sudo chmod -R 700 /var/lib/php5/ and then sudo chown -R www-data /var/lib/php5/ so that the php user has access to the folder.
If you use a connection script, dont forget to use session_start(); at the connection too, had some trouble before noticing that issue.
Maybe if your session path is not working properly you can try session.save_path(path/to/any folder); function as alternative path. If it works you can ask your hosting provider about default path issue.
Just talked to the hosting service, it was an issue at their end.
he said " your account session.save_path was not set as a result issue arise. I set it for you now."
And it works fine after that :)
Maybe it helps others, myself I had
session_regenerate_id(false);
I removed it and all ok!
after login was ok... ouch!
I had similar issue and with the cookie domain:
ini_set('session.cookie_domain', '.domain.com');
the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.
The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.
session_set_cookie_params(0)
I encountered this issue today. the issue has to do with the $config['base_url'] . I noticed htpp://www.domain.com and http://example.com was the issue. to fix , always set your base_url to http://www.example.com
I was also facing the same problem i did the following steps to resolve the issue
I edited the file /etc/php.ini and searched the path session.save_path = "/var/lib/php/session" you have to give your session info
2 After that just changed the permission given below *chown root.apache /var/lib/php/session *
That's it. These above steps resolve my issue
Ensure values you write to your session are simple types. Complex types can cause all session changes to be dropped from memory.
I made the mistake of accidentally setting a session variable with an object value. This prevented the session from serializing and saving. The session appeared to be valid until the page refreshed.
A good way to verify this is to do a var_dump() of $_SESSION and exit() to ensure you are writing exactly what you expect.
echo '<pre>Session: ';
var_dump($_SESSION);
echo '</pre>';
exit();
In my case I could fix the issue by casting my username to string as follows:
$_SESSION['Username'] = (string)$userData->Username;
Cost: 1 nights sleep.
In my case none of above are working then I use ob_clean at the top and it worked like a charm.
ob_clean();
session_start();
Here are the code of my login page where the login script checks for the authenticity of the user and then redirects to inbox page using header function.
<?php
session_start();
include_once('config.php');
$user=htmlentities(stripslashes($_POST['username']));
$password=htmlentities(stripslashes($_POST['password']));
// Some query processing on database
if(($id_user_fetched<=$id_max_fetched) && ($id_user_fetched!=0)){
$_SESSION['loggedIn'] = 'yes';
header("Location:http://xyz/inbox.php?u=$id_user_fetched");
//echo 'Login Successful';
}else{
echo 'Invalid Login';
echo'<br /> Click here to try again';
}
}else{
echo mysqli_error("Login Credentials Incorrect!");
}
?>
The inbox.php page looks like this:
<?php
session_start();
echo 'SESSION ='.$_SESSION['loggedIn'];
if($_SESSION['loggedIn'] != 'yes'){
echo $message = 'you must log in to see this page.';
//header('location:login.php');
}
//REST OF THE CODE
?>
Now with the above code, the inbox.php always shows the output:
SESSION=you must log in to see this page.
Which means that either the session variable is not being setup or the inbox.php is unable to retrieve the session variable. Where am i going wrong?
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 <?php tag before anything else. Also ensure there are no whitespaces/tabs before the opening <?php tag.
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!).
PHP session lost after redirect
I had the same issue for a while and had a very hard time figuring it out. My problem was that I had the site working for a while with the sessions working right, and then all of the sudden everything broke.
Apparently, your session_save_path(), for me it was /var/lib/php5/, needs to have correct permissions (the user running php, eg www-data needs write access to the directory). I accidentally changed it, breaking sessions completely.
Run sudo chmod -R 700 /var/lib/php5/ and then sudo chown -R www-data /var/lib/php5/ so that the php user has access to the folder.
If you use a connection script, dont forget to use session_start(); at the connection too, had some trouble before noticing that issue.
Maybe if your session path is not working properly you can try session.save_path(path/to/any folder); function as alternative path. If it works you can ask your hosting provider about default path issue.
Just talked to the hosting service, it was an issue at their end.
he said " your account session.save_path was not set as a result issue arise. I set it for you now."
And it works fine after that :)
Maybe it helps others, myself I had
session_regenerate_id(false);
I removed it and all ok!
after login was ok... ouch!
I had similar issue and with the cookie domain:
ini_set('session.cookie_domain', '.domain.com');
the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.
The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.
session_set_cookie_params(0)
I encountered this issue today. the issue has to do with the $config['base_url'] . I noticed htpp://www.domain.com and http://example.com was the issue. to fix , always set your base_url to http://www.example.com
I was also facing the same problem i did the following steps to resolve the issue
I edited the file /etc/php.ini and searched the path session.save_path = "/var/lib/php/session" you have to give your session info
2 After that just changed the permission given below *chown root.apache /var/lib/php/session *
That's it. These above steps resolve my issue
Ensure values you write to your session are simple types. Complex types can cause all session changes to be dropped from memory.
I made the mistake of accidentally setting a session variable with an object value. This prevented the session from serializing and saving. The session appeared to be valid until the page refreshed.
A good way to verify this is to do a var_dump() of $_SESSION and exit() to ensure you are writing exactly what you expect.
echo '<pre>Session: ';
var_dump($_SESSION);
echo '</pre>';
exit();
In my case I could fix the issue by casting my username to string as follows:
$_SESSION['Username'] = (string)$userData->Username;
Cost: 1 nights sleep.
In my case none of above are working then I use ob_clean at the top and it worked like a charm.
ob_clean();
session_start();
Checked all over the web and tried all possible solutions written about problems with sessions.
I have 3 pages: the 1st page reads some data from redirected form and stores 4 variables in session. Here is first session id generated and if I check print_r($_SESSION) all is ok.
The form from this page on submission goes to 2nd page where data is stored in mysql database (no session manipulation here), and then "meta" redirects to 3rd page.
Here I try to read variables from session, but instead a new session is generated.
If I look in my server tmp dir both sessions are here.
Why is new session generated instead of reading from first session?
tried page encoding: ANSI, UTF-8 w BOM, UTF-8 wo BOM
tried script that was written in php.net session manual
Any other ideas?
Code is simple session like this:
1st php
session_start();
$_SESSION['id'] = $id;
2nd page tried
session_start();
print_r($_SESSION);
output is Array{ id -> } so only empty variable
3rd page
session_start();
$id = $_SESSION['id'];
echo $id;
and output is ''
It looks like you set the $_SESSION['id'] empty with
$_SESSION['id'] = $id;
cause $id is empty in your Script. Remove this line.
I had the same issue for a while and had a very hard time figuring it out. My problem was that I had the site working for a while with the sessions working right, and then all of the sudden everything broke.
Apparently, your session_save_path(), for me it was /var/lib/php5/, needs to have 777 chmod permissions. I accidentally changed it, breaking sessions completely.
To fix, just do sudo chmod -R 777 /var/lib/php5/ (or whatever your session_save_path() is) on linux.
However issues with sessions are very strange and can be caused by a myriad of reasons...