PHP session lost after redirect - php

How do I resolve the problem of losing a session after a redirect in PHP?
Recently, I encountered a very common problem of losing session after redirect. And after searching through this website I can still find no solution (although this came the closest).
Update
I have found the answer and I thought I'd post it here to help anyone experiencing the same problem.

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 <?php declaration before anything else. Also ensure there are no whitespaces/tabs before the opening <?php declaration.
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!)
Now, these are the most common mistakes, but if they didn't do the trick, the problem is most likely to do with your hosting company. If everything works on localhost but not on your remote/testing server, then this is most likely the culprit. So check the knowledge base of your hosting provider (also try their forums etc). For companies like FatCow and iPage, they require you to specify session_save_path. So like this:
session_save_path('"your home directory path"/cgi-bin/tmp');
session_start();
(replace "your home directory path" with your actual home directory path. This is usually within your control panel (or equivalent), but you can also create a test.php file on your root directory and type:
<?php echo $_SERVER['SCRIPT_FILENAME']; ?>
The bit before 'test.php' is your home directory path. And of course, make sure that the folder actually exists within your root directory. (Some programs do not upload empty folders when synchronizing)

you should use "exit" after header-call
header('Location: http://www.example.com/?blabla=blubb');
exit;

I tried all possible solutions, but none worked for me! Of course, I am using a shared hosting service.
In the end, I got around the problem by using 'relative url' inside the redirecting header !
header("location: http://example.com/index.php")
nullified the session cookies
header("location: index.php")
worked like a charm !

I had the same problem. I worked on it for several hours and it drove me crazy.
In my case the problem was a 404 called due to a missing favicon.ico in Chrome and Firefox only. The other navigators worked fine.

I was having the same problem. All of a sudden SOME of my session variables would not persist to the next page. Problem turned out to be ( in php7.1) you header location must not have WWW in it, ex https://mysite. is ok, https://www.mysite. will lose that pages session variables. Not all, just that page.

When i use relative path "dir/file.php" with in the header() function in works for me.
I think that the session is not saved for some reason when you redirect using the full url...
//Does retain the session info for some reason
header("Location: dir");
//Does not retain the session for some reason
header("Location: https://mywebz.com/dir")

I had a similar problem, although my context was slightly different.
I had a local development setup on a machine whose hostname was windows and IP address was 192.168.56.2.
I could access the system using either of:
http://localhost/
http://127.0.0.1/
http://windows/
http://192.168.56.2/
After logging in, my PHP code would redirect using:
header('http://windows/');
If the previous domain name used to access the system was not windows, the session data would be lost. I solved this by changing the code to:
header('http://'.$_SERVER['HTTP_HOST'].'/');
It now works regardless of what local domain name or IP address the user puts in.
I hope this may be useful to someone.

I ran into this issue on one particular page. I was setting $_SESSION values in other pages right before redirecting and everything was working fine. But this particular page was not working.
Finally I realized that in this particular page, I was destroying the session at the beginning of the page but never starting it again. So my destroy function changed from:
function sessionKill(){
session_destroy();
}
to:
function sessionKill(){
session_destroy();
session_start();
}
And everything worked!

This stumped me for a long time (and this post was great to find!) but for anyone else who still can't get sessions between page redirects to work...I had to go into the php.ini file and turn cookies on:
session.use_cookies = 1
I thought sessions worked without cookies...in fact I know they SHOULD...but this fixed my problem at least until I can understand what may be going on in the bigger picture.

I've been struggling with this for days, checking/trying all the solutions, but my problem was I didn't call session_start(); again after the redirect. I just assumed the session was 'still alive'.
So don't forget that!

Nothing worked for me but I found what caused the problem (and solved it):
Check your browser cookies and make sure that there are no php session cookies on different subdomains (like one for "www.website.com" and one for "website.com").
This was caused by a javascript that incorrectly used the subdomain to set cookies and to open pages in iframes.

KEY POINT'S
Do not start a session on the return page.
Don't use session variable and not include header.php which user session variable
Just make a link go to home page or profile page after insert payment info and status

I had the same problem and found the easiest way.
I simply redirected to a redirect .html with 1 line of JS
<!DOCTYPE html>
<html>
<script type="text/javascript">
<!--
window.location = "admin_index.php";
//–>
</script>
</html>
instead of PHP
header_remove();
header('Location: admin_login.php');
die;
I hope this helps.
Love
Gram

If you are using session_set_cookie_params() you might want to check if you are passing the fourth param $secure as true. If you are, then you need to access the url using https.
The $secure param being true means the Session is only available within a secure request. This might affect you locally more than in stage or production environments.
Mentioning it because I just spent most of today trying to find this issue, and this is what solved it for me. I was just added to this project and no one mentioned that it required https.
So you can either use https locally, or you can set the $secure param to FALSE and then use http locally. Just be sure to set it back to true when you push your changes up.
Depending on your local server, you might have to edit DocumentRoot in the httpd-ssl.conf of the server so that your local url is served https.

Another possible reason:
That is my server storage space. My server disk space become full. So, I have removed few files and folders in my server and tried.
It was worked!!!
I am saving my session in AWS Dynamo DB, but it still expects some space in my server to process the session. Not sure why!!!

ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
Too late to reply but this worked for me

To me this was permission error and this resolved it:
chown -R nginx:nginx /var/opt/remi/php73/lib/php/session
I have tested a few hours on PHP and the last test I did was that I created two files session1.php and session2.php.
session1.php:
session_start();
$_SESSION["user"] = 123;
header("Location: session2.php");
session2.php:
session_start();
print_r($_SESSION);
and it was printing an empty array.
At this point, I thought it could be a server issue and in fact, it was.
Hope this helps someone.

Verify that your session is not Strict. If it is, when you come back, like coming back from Stripe, it regenerate the session.
Use This:
ini_set('session.cookie_samesite', 'Lax');

I also had the same issue with the redirect not working and tried all the solutions I could find, my header redirect was being used in a form.
I solved it by putting the header redirect in a different php page 'signin_action.php' and passing the variables parameters through I wanted in url parameters and then reassigning them in the 'signin_action.php' form.
signin.php
if($stmt->num_rows>0) {
$_SESSION['username'] = $_POST['username'];
echo '<script>window.location.href = "http://'.$root.'/includes/functions/signin_action.php?username='.$_SESSION['username'].'";</script>';
error_reporting(E_ALL);
signin_action.php
<?php
require('../../config/init.php');
$_SESSION['username'] = $_GET['username'];
if ($_SESSION['username']) {
echo '<script>window.location.href = "http://'.$root.'/user/index.php";</script>';
exit();
} else {
echo 'Session not set';
}
?>
It is not a beautiful work-around but it worked.

For me the error was that I tried to save an unserialisable object in the session so that an exception was thrown while trying to write the session. But since all my error handling code had already ceased any operation I never saw the error.
I could find it in the Apache error logs, though.

Just for the record... I had this problem and after a few hours of trying everything the problem was that the disk was full, and php sessions could not be written into the tmp directory... so if you have this problem check that too...

For me, Firefox has stored session id (PHPSESSID) in a cookie, but Google Chrome has used GET or POST parameter.
So you only have to ensure that the returning script (for me: paypal checkout) commit PHPSESSID in url or POST parameter.

After trying many solutions here on SO and other blogs... what worked for me was adding .htaccess to my website root.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursitename.com$
RewriteRule ^.*$ "http\:\/\/www\.yoursitename\.com" [R=301,L]

If you're using Wordpress, I had to add this hook and start the session on init:
function register_my_session() {
if (!session_id()) {
session_start();
}
}
add_action('init', 'register_my_session');

First of all, make sure you are calling session_start() before using $_SESSION variable.
If you have disabled error reporting, try to turn in on and see the result.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
The most common reasons that aren't mentioned in #dayuloli's answer:
Disk space problem. Make sure your disk space is not full, you need some space to store session files.
Session directory may not be writable. You can check it with is_writable(session_save_path())

I was having the same problem and I went nuts searching in my code for the answer. Finally I found my hosting recently updated the PHP version on my server and didn't correctly set up the session_save_path parameter on the php.ini file.
So, if someone reads this, please check php.ini config before anything else.

Make sure session_write_close is not called between session_start() and when you set your session.
session_start();
[...]
session_write_close();
[...]
$_SESSION['name']='Bob'; //<-- won't save

If you are using Laravel and you experience this issue, what you need is to save your session data before redirecting.
session()->save();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;

Now that GDPR is a thing, people visiting this question probably use a cookie script. Well, that script caused the problem for me. Apparently, PHP uses a cookie called PHPSESSID to track the session. If that script deletes it, you lose your data.
I used this cookie script. It has an option to enable "essential" cookies. I added PHPSESSID to the list, the script stopped deleting the cookie, and everything started to work again.
You could probably enable some PHP setting to avoid using PHPSESSID, but if your cookie script is the cause of the problem, why not fix that.

I fixed this problem after many days of debugging and it was all because my return URL coming from PayPal Express Checkout didn't have a 'www'. Chrome recognized that the domains should be treated the same but other browsers sometimes didn't. When using sessions/cookies and absolute paths, don't forget the 'www'!

Related

PHP session variables lost after header() redirect [duplicate]

How do I resolve the problem of losing a session after a redirect in PHP?
Recently, I encountered a very common problem of losing session after redirect. And after searching through this website I can still find no solution (although this came the closest).
Update
I have found the answer and I thought I'd post it here to help anyone experiencing the same problem.
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 <?php declaration before anything else. Also ensure there are no whitespaces/tabs before the opening <?php declaration.
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!)
Now, these are the most common mistakes, but if they didn't do the trick, the problem is most likely to do with your hosting company. If everything works on localhost but not on your remote/testing server, then this is most likely the culprit. So check the knowledge base of your hosting provider (also try their forums etc). For companies like FatCow and iPage, they require you to specify session_save_path. So like this:
session_save_path('"your home directory path"/cgi-bin/tmp');
session_start();
(replace "your home directory path" with your actual home directory path. This is usually within your control panel (or equivalent), but you can also create a test.php file on your root directory and type:
<?php echo $_SERVER['SCRIPT_FILENAME']; ?>
The bit before 'test.php' is your home directory path. And of course, make sure that the folder actually exists within your root directory. (Some programs do not upload empty folders when synchronizing)
you should use "exit" after header-call
header('Location: http://www.example.com/?blabla=blubb');
exit;
I tried all possible solutions, but none worked for me! Of course, I am using a shared hosting service.
In the end, I got around the problem by using 'relative url' inside the redirecting header !
header("location: http://example.com/index.php")
nullified the session cookies
header("location: index.php")
worked like a charm !
I had the same problem. I worked on it for several hours and it drove me crazy.
In my case the problem was a 404 called due to a missing favicon.ico in Chrome and Firefox only. The other navigators worked fine.
I was having the same problem. All of a sudden SOME of my session variables would not persist to the next page. Problem turned out to be ( in php7.1) you header location must not have WWW in it, ex https://mysite. is ok, https://www.mysite. will lose that pages session variables. Not all, just that page.
When i use relative path "dir/file.php" with in the header() function in works for me.
I think that the session is not saved for some reason when you redirect using the full url...
//Does retain the session info for some reason
header("Location: dir");
//Does not retain the session for some reason
header("Location: https://mywebz.com/dir")
I had a similar problem, although my context was slightly different.
I had a local development setup on a machine whose hostname was windows and IP address was 192.168.56.2.
I could access the system using either of:
http://localhost/
http://127.0.0.1/
http://windows/
http://192.168.56.2/
After logging in, my PHP code would redirect using:
header('http://windows/');
If the previous domain name used to access the system was not windows, the session data would be lost. I solved this by changing the code to:
header('http://'.$_SERVER['HTTP_HOST'].'/');
It now works regardless of what local domain name or IP address the user puts in.
I hope this may be useful to someone.
I ran into this issue on one particular page. I was setting $_SESSION values in other pages right before redirecting and everything was working fine. But this particular page was not working.
Finally I realized that in this particular page, I was destroying the session at the beginning of the page but never starting it again. So my destroy function changed from:
function sessionKill(){
session_destroy();
}
to:
function sessionKill(){
session_destroy();
session_start();
}
And everything worked!
This stumped me for a long time (and this post was great to find!) but for anyone else who still can't get sessions between page redirects to work...I had to go into the php.ini file and turn cookies on:
session.use_cookies = 1
I thought sessions worked without cookies...in fact I know they SHOULD...but this fixed my problem at least until I can understand what may be going on in the bigger picture.
I've been struggling with this for days, checking/trying all the solutions, but my problem was I didn't call session_start(); again after the redirect. I just assumed the session was 'still alive'.
So don't forget that!
Nothing worked for me but I found what caused the problem (and solved it):
Check your browser cookies and make sure that there are no php session cookies on different subdomains (like one for "www.website.com" and one for "website.com").
This was caused by a javascript that incorrectly used the subdomain to set cookies and to open pages in iframes.
KEY POINT'S
Do not start a session on the return page.
Don't use session variable and not include header.php which user session variable
Just make a link go to home page or profile page after insert payment info and status
I had the same problem and found the easiest way.
I simply redirected to a redirect .html with 1 line of JS
<!DOCTYPE html>
<html>
<script type="text/javascript">
<!--
window.location = "admin_index.php";
//–>
</script>
</html>
instead of PHP
header_remove();
header('Location: admin_login.php');
die;
I hope this helps.
Love
Gram
If you are using session_set_cookie_params() you might want to check if you are passing the fourth param $secure as true. If you are, then you need to access the url using https.
The $secure param being true means the Session is only available within a secure request. This might affect you locally more than in stage or production environments.
Mentioning it because I just spent most of today trying to find this issue, and this is what solved it for me. I was just added to this project and no one mentioned that it required https.
So you can either use https locally, or you can set the $secure param to FALSE and then use http locally. Just be sure to set it back to true when you push your changes up.
Depending on your local server, you might have to edit DocumentRoot in the httpd-ssl.conf of the server so that your local url is served https.
Another possible reason:
That is my server storage space. My server disk space become full. So, I have removed few files and folders in my server and tried.
It was worked!!!
I am saving my session in AWS Dynamo DB, but it still expects some space in my server to process the session. Not sure why!!!
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
Too late to reply but this worked for me
To me this was permission error and this resolved it:
chown -R nginx:nginx /var/opt/remi/php73/lib/php/session
I have tested a few hours on PHP and the last test I did was that I created two files session1.php and session2.php.
session1.php:
session_start();
$_SESSION["user"] = 123;
header("Location: session2.php");
session2.php:
session_start();
print_r($_SESSION);
and it was printing an empty array.
At this point, I thought it could be a server issue and in fact, it was.
Hope this helps someone.
Verify that your session is not Strict. If it is, when you come back, like coming back from Stripe, it regenerate the session.
Use This:
ini_set('session.cookie_samesite', 'Lax');
I also had the same issue with the redirect not working and tried all the solutions I could find, my header redirect was being used in a form.
I solved it by putting the header redirect in a different php page 'signin_action.php' and passing the variables parameters through I wanted in url parameters and then reassigning them in the 'signin_action.php' form.
signin.php
if($stmt->num_rows>0) {
$_SESSION['username'] = $_POST['username'];
echo '<script>window.location.href = "http://'.$root.'/includes/functions/signin_action.php?username='.$_SESSION['username'].'";</script>';
error_reporting(E_ALL);
signin_action.php
<?php
require('../../config/init.php');
$_SESSION['username'] = $_GET['username'];
if ($_SESSION['username']) {
echo '<script>window.location.href = "http://'.$root.'/user/index.php";</script>';
exit();
} else {
echo 'Session not set';
}
?>
It is not a beautiful work-around but it worked.
For me the error was that I tried to save an unserialisable object in the session so that an exception was thrown while trying to write the session. But since all my error handling code had already ceased any operation I never saw the error.
I could find it in the Apache error logs, though.
Just for the record... I had this problem and after a few hours of trying everything the problem was that the disk was full, and php sessions could not be written into the tmp directory... so if you have this problem check that too...
For me, Firefox has stored session id (PHPSESSID) in a cookie, but Google Chrome has used GET or POST parameter.
So you only have to ensure that the returning script (for me: paypal checkout) commit PHPSESSID in url or POST parameter.
After trying many solutions here on SO and other blogs... what worked for me was adding .htaccess to my website root.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursitename.com$
RewriteRule ^.*$ "http\:\/\/www\.yoursitename\.com" [R=301,L]
If you're using Wordpress, I had to add this hook and start the session on init:
function register_my_session() {
if (!session_id()) {
session_start();
}
}
add_action('init', 'register_my_session');
First of all, make sure you are calling session_start() before using $_SESSION variable.
If you have disabled error reporting, try to turn in on and see the result.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
The most common reasons that aren't mentioned in #dayuloli's answer:
Disk space problem. Make sure your disk space is not full, you need some space to store session files.
Session directory may not be writable. You can check it with is_writable(session_save_path())
I was having the same problem and I went nuts searching in my code for the answer. Finally I found my hosting recently updated the PHP version on my server and didn't correctly set up the session_save_path parameter on the php.ini file.
So, if someone reads this, please check php.ini config before anything else.
Make sure session_write_close is not called between session_start() and when you set your session.
session_start();
[...]
session_write_close();
[...]
$_SESSION['name']='Bob'; //<-- won't save
If you are using Laravel and you experience this issue, what you need is to save your session data before redirecting.
session()->save();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
Now that GDPR is a thing, people visiting this question probably use a cookie script. Well, that script caused the problem for me. Apparently, PHP uses a cookie called PHPSESSID to track the session. If that script deletes it, you lose your data.
I used this cookie script. It has an option to enable "essential" cookies. I added PHPSESSID to the list, the script stopped deleting the cookie, and everything started to work again.
You could probably enable some PHP setting to avoid using PHPSESSID, but if your cookie script is the cause of the problem, why not fix that.
I fixed this problem after many days of debugging and it was all because my return URL coming from PayPal Express Checkout didn't have a 'www'. Chrome recognized that the domains should be treated the same but other browsers sometimes didn't. When using sessions/cookies and absolute paths, don't forget the 'www'!

Why won't my $_SESSION variable change for each field [duplicate]

How do I resolve the problem of losing a session after a redirect in PHP?
Recently, I encountered a very common problem of losing session after redirect. And after searching through this website I can still find no solution (although this came the closest).
Update
I have found the answer and I thought I'd post it here to help anyone experiencing the same problem.
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 <?php declaration before anything else. Also ensure there are no whitespaces/tabs before the opening <?php declaration.
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!)
Now, these are the most common mistakes, but if they didn't do the trick, the problem is most likely to do with your hosting company. If everything works on localhost but not on your remote/testing server, then this is most likely the culprit. So check the knowledge base of your hosting provider (also try their forums etc). For companies like FatCow and iPage, they require you to specify session_save_path. So like this:
session_save_path('"your home directory path"/cgi-bin/tmp');
session_start();
(replace "your home directory path" with your actual home directory path. This is usually within your control panel (or equivalent), but you can also create a test.php file on your root directory and type:
<?php echo $_SERVER['SCRIPT_FILENAME']; ?>
The bit before 'test.php' is your home directory path. And of course, make sure that the folder actually exists within your root directory. (Some programs do not upload empty folders when synchronizing)
you should use "exit" after header-call
header('Location: http://www.example.com/?blabla=blubb');
exit;
I tried all possible solutions, but none worked for me! Of course, I am using a shared hosting service.
In the end, I got around the problem by using 'relative url' inside the redirecting header !
header("location: http://example.com/index.php")
nullified the session cookies
header("location: index.php")
worked like a charm !
I had the same problem. I worked on it for several hours and it drove me crazy.
In my case the problem was a 404 called due to a missing favicon.ico in Chrome and Firefox only. The other navigators worked fine.
I was having the same problem. All of a sudden SOME of my session variables would not persist to the next page. Problem turned out to be ( in php7.1) you header location must not have WWW in it, ex https://mysite. is ok, https://www.mysite. will lose that pages session variables. Not all, just that page.
When i use relative path "dir/file.php" with in the header() function in works for me.
I think that the session is not saved for some reason when you redirect using the full url...
//Does retain the session info for some reason
header("Location: dir");
//Does not retain the session for some reason
header("Location: https://mywebz.com/dir")
I had a similar problem, although my context was slightly different.
I had a local development setup on a machine whose hostname was windows and IP address was 192.168.56.2.
I could access the system using either of:
http://localhost/
http://127.0.0.1/
http://windows/
http://192.168.56.2/
After logging in, my PHP code would redirect using:
header('http://windows/');
If the previous domain name used to access the system was not windows, the session data would be lost. I solved this by changing the code to:
header('http://'.$_SERVER['HTTP_HOST'].'/');
It now works regardless of what local domain name or IP address the user puts in.
I hope this may be useful to someone.
I ran into this issue on one particular page. I was setting $_SESSION values in other pages right before redirecting and everything was working fine. But this particular page was not working.
Finally I realized that in this particular page, I was destroying the session at the beginning of the page but never starting it again. So my destroy function changed from:
function sessionKill(){
session_destroy();
}
to:
function sessionKill(){
session_destroy();
session_start();
}
And everything worked!
This stumped me for a long time (and this post was great to find!) but for anyone else who still can't get sessions between page redirects to work...I had to go into the php.ini file and turn cookies on:
session.use_cookies = 1
I thought sessions worked without cookies...in fact I know they SHOULD...but this fixed my problem at least until I can understand what may be going on in the bigger picture.
I've been struggling with this for days, checking/trying all the solutions, but my problem was I didn't call session_start(); again after the redirect. I just assumed the session was 'still alive'.
So don't forget that!
Nothing worked for me but I found what caused the problem (and solved it):
Check your browser cookies and make sure that there are no php session cookies on different subdomains (like one for "www.website.com" and one for "website.com").
This was caused by a javascript that incorrectly used the subdomain to set cookies and to open pages in iframes.
KEY POINT'S
Do not start a session on the return page.
Don't use session variable and not include header.php which user session variable
Just make a link go to home page or profile page after insert payment info and status
I had the same problem and found the easiest way.
I simply redirected to a redirect .html with 1 line of JS
<!DOCTYPE html>
<html>
<script type="text/javascript">
<!--
window.location = "admin_index.php";
//–>
</script>
</html>
instead of PHP
header_remove();
header('Location: admin_login.php');
die;
I hope this helps.
Love
Gram
If you are using session_set_cookie_params() you might want to check if you are passing the fourth param $secure as true. If you are, then you need to access the url using https.
The $secure param being true means the Session is only available within a secure request. This might affect you locally more than in stage or production environments.
Mentioning it because I just spent most of today trying to find this issue, and this is what solved it for me. I was just added to this project and no one mentioned that it required https.
So you can either use https locally, or you can set the $secure param to FALSE and then use http locally. Just be sure to set it back to true when you push your changes up.
Depending on your local server, you might have to edit DocumentRoot in the httpd-ssl.conf of the server so that your local url is served https.
Another possible reason:
That is my server storage space. My server disk space become full. So, I have removed few files and folders in my server and tried.
It was worked!!!
I am saving my session in AWS Dynamo DB, but it still expects some space in my server to process the session. Not sure why!!!
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
Too late to reply but this worked for me
To me this was permission error and this resolved it:
chown -R nginx:nginx /var/opt/remi/php73/lib/php/session
I have tested a few hours on PHP and the last test I did was that I created two files session1.php and session2.php.
session1.php:
session_start();
$_SESSION["user"] = 123;
header("Location: session2.php");
session2.php:
session_start();
print_r($_SESSION);
and it was printing an empty array.
At this point, I thought it could be a server issue and in fact, it was.
Hope this helps someone.
Verify that your session is not Strict. If it is, when you come back, like coming back from Stripe, it regenerate the session.
Use This:
ini_set('session.cookie_samesite', 'Lax');
I also had the same issue with the redirect not working and tried all the solutions I could find, my header redirect was being used in a form.
I solved it by putting the header redirect in a different php page 'signin_action.php' and passing the variables parameters through I wanted in url parameters and then reassigning them in the 'signin_action.php' form.
signin.php
if($stmt->num_rows>0) {
$_SESSION['username'] = $_POST['username'];
echo '<script>window.location.href = "http://'.$root.'/includes/functions/signin_action.php?username='.$_SESSION['username'].'";</script>';
error_reporting(E_ALL);
signin_action.php
<?php
require('../../config/init.php');
$_SESSION['username'] = $_GET['username'];
if ($_SESSION['username']) {
echo '<script>window.location.href = "http://'.$root.'/user/index.php";</script>';
exit();
} else {
echo 'Session not set';
}
?>
It is not a beautiful work-around but it worked.
For me the error was that I tried to save an unserialisable object in the session so that an exception was thrown while trying to write the session. But since all my error handling code had already ceased any operation I never saw the error.
I could find it in the Apache error logs, though.
Just for the record... I had this problem and after a few hours of trying everything the problem was that the disk was full, and php sessions could not be written into the tmp directory... so if you have this problem check that too...
For me, Firefox has stored session id (PHPSESSID) in a cookie, but Google Chrome has used GET or POST parameter.
So you only have to ensure that the returning script (for me: paypal checkout) commit PHPSESSID in url or POST parameter.
After trying many solutions here on SO and other blogs... what worked for me was adding .htaccess to my website root.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursitename.com$
RewriteRule ^.*$ "http\:\/\/www\.yoursitename\.com" [R=301,L]
If you're using Wordpress, I had to add this hook and start the session on init:
function register_my_session() {
if (!session_id()) {
session_start();
}
}
add_action('init', 'register_my_session');
First of all, make sure you are calling session_start() before using $_SESSION variable.
If you have disabled error reporting, try to turn in on and see the result.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
The most common reasons that aren't mentioned in #dayuloli's answer:
Disk space problem. Make sure your disk space is not full, you need some space to store session files.
Session directory may not be writable. You can check it with is_writable(session_save_path())
I was having the same problem and I went nuts searching in my code for the answer. Finally I found my hosting recently updated the PHP version on my server and didn't correctly set up the session_save_path parameter on the php.ini file.
So, if someone reads this, please check php.ini config before anything else.
Make sure session_write_close is not called between session_start() and when you set your session.
session_start();
[...]
session_write_close();
[...]
$_SESSION['name']='Bob'; //<-- won't save
If you are using Laravel and you experience this issue, what you need is to save your session data before redirecting.
session()->save();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
Now that GDPR is a thing, people visiting this question probably use a cookie script. Well, that script caused the problem for me. Apparently, PHP uses a cookie called PHPSESSID to track the session. If that script deletes it, you lose your data.
I used this cookie script. It has an option to enable "essential" cookies. I added PHPSESSID to the list, the script stopped deleting the cookie, and everything started to work again.
You could probably enable some PHP setting to avoid using PHPSESSID, but if your cookie script is the cause of the problem, why not fix that.
I fixed this problem after many days of debugging and it was all because my return URL coming from PayPal Express Checkout didn't have a 'www'. Chrome recognized that the domains should be treated the same but other browsers sometimes didn't. When using sessions/cookies and absolute paths, don't forget the 'www'!

Session doesn't work after redirect

My code looks like this:
...
$_SESSION['message']="something";
header('location:http://url/somewhere');
exit;
As you can see, I have an exit at the end of it. And that is the problem. It doesn´t work although I have an exit there.
I have this problem only on my localhost. At the online server it works well. In the errorlog it only shows "undefined index message". A few days ago I installed new Apache 2.4 and PHP 5.4.
Don't forget to start your session on every page you are going to use it:
if(!isset($_SESSION)){
session_start();
}
Please be sure to add "session_start();" to the beginning of every page that processes any sort of session data. Another thing to check would be to make sure you are setting the session variable properly. Also, when using header to redirect, make sure there is NO white space in the beginning of your document.

PHP session is empty even when Session ID is right

Yesterday I searched almost all topics about php sessions, I looked over manual and it still didn't work. I stayed up very late because of that.
Scenario is: I log in using standard html form. My session is populated with some variables and it work fine. Then I use Flash uploadify to upload some photos and I pass with parametrs - PHPSESSID. My php script does not recognize session. It sees it as empty. Then I try to get that session with different client such as Firefox or Opera and it is empty too. Then I try to get that session with different Chrome tab and it works
As you see my only protection is by IP. I don't scan other things so this should work when good PHPSESSID is passed and client IP is matching regardless of client type, version etc.
This is init_session.php, file I include everytime at the begining of other files. Therefore I know that Session ID is beeing passed with Flash. But then session is empty.
Directory is set on the top, and path is direct so there shouldn't be any problems with that. It also doesn't work when save path is default. I also turned of session autostart and session use only cookies. It didn't change a thing except I need to set cookie manually.
Is there something here I can try? I think I ran out of options.
EDIT:
I forgot about most importat thing i think that turning off suhosin.session.cryptua will resolve case but i can't turn it off using ini_set, is there any other way? It seems that this option encrypts session using user-agent field wich would be the case.
ini_set('session.auto_start', '0');
ini_set('session.save_path','/public_html/nowy/tmp');
if (isset($_POST["PHPSESSID"])) {
session_id($_POST["PHPSESSID"]);
} elseif (isset($_COOKIE['PHPSESSID'])) {
session_id($_COOKIE["PHPSESSID"]);
} elseif (isset($_GET["PHPSESSID"])) {
session_id($_GET["PHPSESSID"]);
}
session_start();
setcookie("PHPSESSID", session_id(), time()+3600, "/");
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = 0;
}
if (!isset($_SESSION['initiate'])) {
session_regenerate_id();
$_SESSION['initiate'] = true;
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}
echo ini_get('session.save_path').'<br />';
echo $_POST["PHPSESSID"];
print_r($_SESSION);
RESOLVED
This problem has been solved. I couldn't set cryptua off because I needed to copy oryginal php5.ini and replace some variables to get it working.
The problem was as expected suhosin.session.cryptua
As Frode suggested in his comment I'm leaving this as an answer.
This can happen when using any flash script, not just uploadify. Any other flash uploader such as SWFUpload won't get the session unless user-agent field is the same.
This happens when your server has suhosin patch installed but it seems that sometimes this problem doesn't occur even when setting suhosin.session.cryptua is enabled as alecgorge suggested. Although I am not convinced about that. Of course you can pass to flash this variable using php scripts to uncover user-agent of user browser and then flash can disguise himself as the same browser but it's not elegant solution and I don't know actionscript so I can't say if flash can actually do it.
Very important:
There are actually two settings that can fix this security patch.
suhosin.session.encrypt
suhosin.session.cryptua
If the first one is disabled then session is not encrypted at all so problem won't occur. It's not recommended to disable this. If we disable only the second one then session will be encrypted but encryption won't relay on user-agent field. This means that any browser or http client can get any session. Therefore it's recommended to put some other security fields. Suhosin can handle also session ip protection so I recommend to enable suhosin.session.cryptraddr. Other settings can be found here:
Suhosin configuration
To resolve this issue I suggest:
Check phpinfo() if suhosin is installed. If not then problem won't occur.
If suhosin is installed and suhosin.session.cryptua and suhosin.session.encrypt are enabled then copy existing and working php.ini. It's on the top of php info page: Loaded Configuration File /public_html/php5.ini
Create your own php.ini and set:
suhosin.session.encrypt = On
suhosin.session.cryptraddr = On
suhosin.session.cryptua = Off
Usually with Uploadify I have to do something like this:
$('#uploadify').uploadify('scriptData':{'session_name':'<?php echo session_id(); ?>'}});
On the client in conjunction with something like this on the server side:
if($_POST['session_name']) {
session_id($_POST['session_name']);
}
session_start();

PHP Session data not being saved

I have one of those "I swear I didn't touch the server" situations. I honestly didn't touch any of the php scripts. The problem I am having is that php data is not being saved across different pages or page refreshes. I know a new session is being created correctly because I can set a session variable (e.g. $_SESSION['foo'] = "foo" and print it back out on the same page just fine. But when I try to use that same variable on another page it is not set! Is there any php functions or information I can use on my hosts server to see what is going on?
Here is an example script that does not work on my hosts' server as of right now:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;
echo "views = ". $_SESSION['views'];
echo '<p>Refresh</p>';
?>
The 'views' variable never gets incremented after doing a page refresh. I'm thinking this is a problem on their side, but I wanted to make sure I'm not a complete idiot first.
Here is the phpinfo() for my hosts' server (PHP Version 4.4.7):
Thanks for all the helpful info. It turns out that my host changed servers and started using a different session save path other than /var/php_sessions which didn't exist anymore. A solution would have been to declare ini_set(' session.save_path','SOME WRITABLE PATH'); in all my script files but that would have been a pain. I talked with the host and they explicitly set the session path to a real path that did exist. Hope this helps anyone having session path troubles.
Check to make sure you are not mixing https:// with http://. Session variables do not flow between secure and insecure sessions.
Had same problem - what happened to me is our server admin changed the session.cookie_secure boolean to On, which means that cookies will only be sent over a secure connection. Since the cookie was not being found, php was creating a new session every time, thus session variables were not being seen.
Use phpinfo() and check the session.* settings.
Maybe the information is stored in cookies and your browser does not accept cookies, something like that.
Check that first and come back with the results.
You can also do a print_r($_SESSION); to have a dump of this variable and see the content....
Regarding your phpinfo(), is the session.save_path a valid one? Does your web server have write access to this directory?
Hope this helps.
I had following problem
index.php
<?
session_start();
$_SESSION['a'] = 123;
header('location:index2.php');
?>
index2.php
<?
session_start();
echo $_SESSION['a'];
?>
The variable $_SESSION['a'] was not set correctly. Then I have changed the index.php acordingly
<?
session_start();
$_SESSION['a'] = 123;
session_write_close();
header('location:index2.php');
?>
I dont know what this internally means, I just explain it to myself that the session variable change was not quick enough :)
Check to see if the session save path is writable by the web server.
Make sure you have cookies turned on.. (I forget when I turn them off to test something)
Use firefox with the firebug extension to see if the cookie is being set and transmitted back.
And on a unrelated note, start looking at php5, because php 4.4.9 is the last of the php4 series.
Check who the group and owner are of the folder where the script runs. If the group id or user id are wrong, for example, set to root, it will cause sessions to not be saved properly.
Check the value of "views" when before you increment it. If, for some bizarre reason, it's getting set to a string, then when you add 1 to it, it'll always return 1.
if (isset($_SESSION['views'])) {
if (!is_numeric($_SESSION['views'])) {
echo "CRAP!";
}
++$_SESSION['views'];
} else {
$_SESSION['views'] = 1;
}
Well, we can eliminate code error because I tested the code on my own server (PHP 5).
Here's what to check for:
Are you calling session_unset() or session_destroy() anywhere? These functions will delete the session data immediately. If I put these at the end of my script, it begins behaving exactly like you describe.
Does it act the same in all browsers? If it works on one browser and not another, you may have a configuration problem on the nonfunctioning browser (i.e. you turned off cookies and forgot to turn them on, or are blocking cookies by mistake).
Is the session folder writable? You can't test this with is_writable(), so you'll need to go to the folder (from phpinfo() it looks like /var/php_sessions) and make sure sessions are actually getting created.
If you set a session in php5, then try to read it on a php4 page, it might not look in the correct place! Make the pages the same php version or set the session_path.
I spent ages looking for the answer for a similar problem. It wasn't an issue with the code or the setup, as a very similar code worked perfectly in another .php on the same server. Turned out the problem was caused by a very large amount of data being saved into the session in this page. In one place we had a line like this:$_SESSION['full_list'] = $full_list where $full_list was an array of data loaded from the database; each row was an array of about 150 elements. When the code was initially written a couple of years ago, the DB only contained about 1000 rows, so the $full_list contained about 100 elements, each being an array of about 20 elements. With time, the 20 elements turned into 150 and 1000 rows turned into 17000, so the code was storing close to 64 meg of data into the session. Apparently, with this amount of data being stored, it refused to store anything else. Once we changed the code to deal with data locally without saving it into the session, everything worked perfectly.
I know one solution I found (OSX with Apache 1 and just switched to PHP5) when I had a similar problem was that unsetting 1 specific key (ie unset($_SESSION['key']);) was causing it not to save. As soon as I didn't unset that key any more it saved. I have never seen this again, except on that server on another site, but then it was a different variable. Neither were anything special.
Thanks for this one Darryl. This helped me out. I was deleting a session variable, and for some reason it was keeping the session from committing. now i'm just setting it to null instead (which is fine for my app), and it works.
I know one solution I found (OSX with Apache 1 and just switched to PHP5) when I had a similar problem was that unsetting 1 specific key (ie unset($_SESSION['key']);) was causing it not to save. As soon as I didn't unset that key any more it saved. I have never seen this again, except on that server on another site, but then it was a different variable. Neither were anything special.
Here is one common problem I haven't seen addressed in the other comments: is your host running a cache of some sort? If they are automatically caching results in some fashion you would get this sort of behavior.
Just wanted to add a little note that this can also occur if you accidentally miss the session_start() statement on your pages.
Check if you are using session_write_close(); anywhere, I was using this right after another session and then trying to write to the session again and it wasn't working.. so just comment that sh*t out
I had session cookie path set to "//" instead of "/". Firebug is awesome.
Hope it helps somebody.
I had this problem when using secure pages where I was coming from www.domain.com/auth.php that redirected to domain.com/destpage.php. I removed the www from the auth.php link and it worked. This threw me because everything worked otherwise; the session was not set when I arrived at the destination though.
A common issue often overlooked is also that there must be NO other code or extra spacing before the session_start() command.
I've had this issue before where I had a blank line before session_start() which caused it not to work properly.
Adding my solution:
Check if you access the correct domain. I was using www.mysite.com to start the session, and tried to receive it from mysite.com (without the www).
I have solved this by adding a htaccess rewrite of all domains to www to be on the safe side/site.
Also check if you use http or https.
Edit your php.ini.
I think the value of session.gc_probability is 1, so set it to 0.
session.gc_probability=0
Another few things I had to do (I had same problem: no sesson retention after PHP upgrade to 5.4). You many not need these, depending on what your server's php.ini contains (check phpinfio());
session.use_trans_sid=0 ; Do not add session id to URI (osc does this)
session.use_cookies=0; ; ensure cookies are not used
session.use_only_cookies=0 ; ensure sessions are OK to use IMPORTANT
session.save_path=~/tmp/osc; ; Set to same as admin setting
session.auto_start = off; Tell PHP not to start sessions, osc code will do this
Basically, your php.ini should be set to no cookies, and session parameters must be consistent with what osc wants.
You may also need to change a few session code snippets in application_top.php - creating objects where none exist in the tep_session_is_registered(...) calls (e eg. navigation object), set $HTTP_ variables to the newer $_SERVER ones and a few other isset tests for empty objects (google for info). I ended up being able to use the original sessions.php files (includes/classes and includes/functions) with a slightly modified application_top.php to get things going again. The php.ini settings were the main problem, but this of course depends on what your server company has installed as the defaults.

Categories