setcookie not removing cookie - php

I really don't know what the issue is here.
I have a script called "login.php" that works perfectly. It's called with AJAX, and if it returns successfully, the page refreshes and the user is logged in. The cookie is set on that page with
setcookie("main", $row[0], time() + 3600, "/")
Then I have a script called "logout.php". It is called the same way (AJAX and then page refresh). It only has two lines:
<?php
setcookie("main", "", time() - 3600, "/");
echo "Done";
?>
Calling it form the page wasn't working, so I just loaded logout.php in the browser. The output was "done" but checking my cookies in Chrome showed me that the cookie was still set to "1" (which was $row[0]) and to expire at the time set in login.php.
login.php and logout.php are both in the same folder, the root directory, which is the same folder as everything else.
Earlier, this was working, but the only changes I've made are to make the title bar on the website its own file (still in the root directory) and to take the JavaScript functionality for the Logout button, which is just an AJAX call and some jQuery hover effects, and make it its own script file, which is in the _js folder. But I didn't change logout.php at all, so it should still work when I navigate directly to it, right? Is there something wrong with my setcookie command, or what other problem could be causing it?
EDIT: I tried setting it to expire in 100 seconds instead of -3600, and then tried changing its name so I could recognize it as a totally separate cookie. Neither of them made it show up. The cookie simply isn't getting set at all.
EDIT 2: I reverted to the last commit, and everything is working again. I don't know why reorganizing my site by creating some new files (logout.php isn't changed at all) makes a certain script unable to create cookies.

Cookies must be set before any content goes to the client. Make sure you haven't sent anything to the client before calling a setcookie as it's actually a Set-Cookie header coming back through the request.
Something as little as a space in an include file can ruin this. (You said you worked on other files, check that nothing being included has anything such as a debug echo or whitespace outside of your <?php ... ?> brackets)
As a general rule of thumb, if I have a file that is exclusively PHP code I only include the opening tag (<?php) and exempt the last one. PHP will still parse and run, but this avoids any whitespace at the end of the file that may become problematic. e.g.
mycodefile.php
<?php
define('...', ...);
function ...(){ }
Also, you mentioned using chrome. Open your debugger in chrome (ctrl+shft+i) and click the Network tab. Then find your logout call and select it, then click Headers and verify your cookie is being cleared. (likewise you can click Resources and look under Cookies to view any set.

Related

PHP - GET variables sometimes missing on header redirect (cloudflare related?)

I've a strange problem with header() redirects.
There are three pages involved: upload.php (for choosing the file, POST form), doupload.php (add file to server, write to DB etc.) and target.php (doupload.php redirects to that page after successful upload).
My code on doupload.php at the end (the redirecting part):
$id = 5;
header("Location: https://www.mypage.com/target.php?id=".$id."&secondvar=1");
exit();
On normal circumstances it works without problems. But sometimes the connection to my webserver lacks (bad connection) and it needs 5 up to 20 seconds to complete the request.
In this case, all GET variables after 'id=5' are gone.
Example: Should be redirected to
/target.php?id=5&secondvar=1
but it's redirected to
/target.php?id=5
without the rest.
I'm using Cloudflare. Maybe there is a session problem in this cases?
I could add session_start(); to each page, but I don't think that's the problem, because on normal circumstances it works.
I'm very thankful for every help to fix that strange issue.

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'!

PHP session lost after redirect

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'!

Cookies arent being detected in php or javascript

Im not sure where im going wrong. I have a form that when the contents of the form get processed and sent to the database it also sets a cookie
setcookie("bgremkey",$checkkey, time()+2592000);
then it will redirect the user back to the page they came from. All of this works fine (bar the cookie bit)
then i have it set at the top of every page providing there isnt an session active to check to see if the cookie exists and if it does to redirect but it wont work. im sure that the cookie is there but it wont pick it up
<?php
if(isset($_COOKIE['bgremkey']))
{
header("location:'Check.php?cklog=1");
}
?>
<script type="text/javascript" language="JavaScript">
var acookie = ReadCookie("bgremkey");
if(acookie.length != 0)
{
window.location = " Check.php?cklog=1";
}
this code doesnt generate any errors but it also doesnt do anything. i have tried putting it in the of the page but that didnt work so i then tried the body and that didnt work either
the check page does a bunch of other stuff but thats not the problem since the redirect never happens
i checked the cookies through chrome and the cookie exists and its path is / so the problem is definitely with reading them. it exists but for some reason cant be detected
http://php.net/manual/en/function.setcookie.php
setcookie("cookiename","cookievalue", $time); will only set it for the current path
Whereas: setcookie("cookiename","cookievalue", $time,"/"); will set the cookie for all pages/folders on that domain (note the 4th argument containing the path ).
If you press CTRL+SHIFT+J in google chrome, and click on the Resources tab, you can find the cookies and the path it is valid in. I'd check that out. perhaps this is why?

PHP sessions and AJAX request (from injected JS code)

I think I forgetting something in my code but can't find what.
On my server I have simple logging.php file.
If I pass user/password parameters then a new session is created.
If I pass loggout the session is destroyed.
If I pass report the list of current session variables are reported on screen.
If I test the code writing urls in my browser all works fine. First invoke .../logging.php?user=xxx&password=xxx. The session is started and the session variables are reported to me. And finally I destroy the session passing the logout parameter.
If user request a report or a logout and no session exists a HTTP-401 error code is returned to client.
On the other hand I have a piece of JavaScript code that I can inject on web page using a bookmarklet. Once code is injected I show a toolbar where user can write user/password and send to server.
The logging actions seems to works fine, and server returns me a 200 status code, but later if I make a request to logout the server returns me a 401 error, which mean no session exists.
I was using chrome and looking at HTTP request and responses can see that when I logging the server returns in the response different values for PHPSESSIONID.
That means two different AJAX request are considered different sessions. The server seems to not recognize the second request from AJAX as if it was started by the same client.
Repeat, the PHP code works fine if I execute using browser directly but not with AJAX request, so I think I forgetting something in AJAX.
Any ideas?
Thanks in advance.
Update
To be more concise, my problem is calling php from JavaScript. It seems there are no sessions started.
Imagine a very simple PHP code:
logging.php: given a user/password starts a new session and also stores 'user' names as a session variable.
request.php: which returns the user name stored as session variable.
logout.php: which destroys the session.
My first AJAX request start a PHP session. That seems fine because a PHPSESSIONID cookie is returned from server. Also I store the user name as session variable.
The second AJAX request tries to get the user name (stored in the session) but it gets nothing and in addition a new PHPSESSIONID cookie is returned from server.
I know it seems impossible and more when I'm testing using browser url request and works fine, but it's the truth.
I'm forgetting something on AJAX, expiration times or something similar?
Update again
I made some tests and I found the problem but not the solution.
My JS code is injected through a bookmarklet.
When I inject the code in a HTML page from my server, the AJAX requests works fine. The first (logging) request gets a PHPSESSID which is passed in subsequent request to the server.
On the other hand If I load google.com and inject the code, the first (logging) request gets the PHPSESSID too but later it is not sent with next requests.
Anyone has experienced the same issue? which is the problem?
Thanks in advance.
Update again, again
Ok finally I found my problem. Because my JS is injected from a different domain (current page is from domainA and my JS code comes from domainB) cookies are not cross domain, so PHPSESSID can be shared.
A possible soulution is when I logging I will return the PHP session ID in pice of JSON data and use it for subsequent calls.
If I'm correct, you're trying to log in a user by making an AJAX request to a URL, with the username and password provided in the URL? That's not really a safe construction, the password is very vulnerable this way?!
I would advice you to implement jQuery, and transer the login details using the $.POST command:
http://api.jquery.com/jQuery.post/
Make sure all your files (also those requested by AJAX) contain session_start(); on top of the file.
When every file contains session_start(); and you're using the same $_SESSION variables to check if a user is loggedin, it should work!
Are both of your AJAX requests coming from the same page? The requests are Asynchronous, so it may be that the "logged in?" request is returning its result before the "log in" request goes through.
From what you have asked, I hope your code is (at its beginning more or less) something like:
A file logging.php like this:
<?php # file : loggging.php
if(!ini_set('session.auto_start'))
// more stuff
if(!empty($_REQUEST['user']) && !empty($_REQUEST['passwd'])) {
session_regenerate_sid(); // This is important (1)
$_SESSION['user'] = $_REQUEST['user'];
// Whatever
}
A file request.php like this..
<?php # file : request.php
if(!ini_set('session.auto_start'))
// Whatever stuff to process data
var_dump($_SESSION);
// Or a nice foreach($v as $i => $x) {
// echo("[$i] => $x\n<br />");
// } instead :)
And your logout.php should read something like..
<?php # file : logout.php
if(!ini_set('session.auto_start')) session_start();
session_destroy();
You are probably not calling either session_start() or you are calling it twice.
To check this out try this: change all your session_start() lines for:
session_name('MYCoolNewName');
session_start();
Now your session should not read PHPSESSID, instead it should be MYCoolNewName.
If it is not, then your problem is the aforementioned.
(1) I put as important session_regenerate_sid() because opened authenticated sessions are a threat out there. I'll demonstrate it with an example.
Alice visits coolwebsite.com/login.php, which gives her a SID which I'll call AliceSID.
Alice tells Bob to visit coolwebsite.com/login.php?PHPSESSID=AliceSID, and when Bob does Alice could log in his account unless Bob's session was regenerated.

Categories