Hi
I have problems with Google Chrome, while developing a PHP website.
I start a session, and store a flag inside it. But when I reload the page, the session value is not recognized.
What can be wrong? Thanks for reply.
session_start();
if (isset($_SESSION['chrome'])) {
echo 'SESSION OK';
}
else {
$_SESSION['chrome'] = 'yes';
}
This is simple code, but it doesn't work...
I had the exact same problem with Chrome not persisting php sessions on a login system. Found the following article: https://secure.kitserve.org.uk/content/php-session-cookie-problems-google-chrome-and-internet-explorer which says:
When testing a local site in Chromium, you must either access it via IP address (e.g. 127.0.0.1) or set the cookie domain parameter to the empty string.
I hope this helps.
I had exact same problem, but on IIS and ASP.Net Mvc. An F5 would make the session recover, but moving to another page caused the problem again. I posted the answer for another SO question. Try it out and see if works.
I think the answer to this is to use session_name before session_set_cookie_params. For example...
session_name('MySession');
session_set_cookie_params( 3600*24, '/', $_SERVER['HTTP_HOST'], is_https() );
session_cache_expire(60*24); // cache expire 60 mins
Check to see if you deactivated cookies in your browser.
Related
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();
My session is not working in chrome and safari browser and working in firefox. Can anyone explain why this is happening ?
<?php
session_start();
$sessionuser=$_SESSION['user'];
?>
If I print_r($sessionuser) it is not working in chrome or safari browsers bu working in firefox
I'd say that, other than your code has parsing errors, that you would have to use session_start(); before you use $_SESSION[]
It might be that you have forgotten an old session cookie in firefox. I think it is possible to check this with firebug.
Also check da5id's answer, it will fix the parsing error.
Try this
session_start();
$sessionuser=$_SESSION['user'];
echo $sessionuser;
try the following. It works on my chrome in LINUX.
session_start();
$_SESSION['user'] = "hithere";
$sessionuser=$_SESSION['user'];
print_r($sessionuser);
You have to check your browser cookie. Your session not a set If cookie is disabled. You have to go in browser setting and check cookie setting.
Just try
In my case I just reset chrome browser
Go to chrome://settings/ then click advanced then reset
Just clear the cookies in your Google Chrome in the Setting.
Privacy and Security -> Cookies and other site data -> See all cookies and site data
Search by the domain name or IP and delete the existing cookies.
Note: This issue is already solved,
finally I found that it's not cookies
problem, the problem is on
unserialize() function. The serialized
cookie which being the parameter of
that function must be stripslash-ed
first.
Hi there, I have a problem here about PHP Cookies. I'm using PHP Cookies to save user preferences. I've tested my code on my local machine (localhost using XAMPP). Everything's works very well, including the cookies. But when I uploaded it to the live server, the cookies not working at all. It seems that the setcookie() function do not write the cookie value. I've tested by echo-ing the cookie value both on my localhost and on my live server. $_COOKIE[] value on localhost is showing but not with the one in the live server.
I thought maybe it's related to the $expire time zone like the one's in this post http://anupraj.com.np/index.php/php-cookies-not-working-php-cookie-tutorial-and-scirpt/14 . But then I realized that I've set the cookies to expire in 1 month, not only in one hour like on that blog post. So I think that's not the case.
This is the content of setting.php
<?php
$defaultSettings['default_post_to'] = 'both';
$defaultSettings['timesince_style'] = 'simplify';
...
$defaultSettings['display_geo_info'] = 'true';
$defaultSettings['enable_javascript'] = 'true';
if(!isset($_COOKIE['settings'])){
setcookie("settings", serialize($defaultSettings), time()+3600*24*30);
header('Location: index.php');
}
$setting = unserialize($_COOKIE['settings']);
?>
And this is content of index.php
<?php
/*
ini_set ("display_errors", "1");
error_reporting(E_ALL);
*/
session_start();
require_once("settings.php"); // Settings files
require_once('varlib.php'); // Get all possible passed variable
require_once('auth.php'); // Check for channel login status
// If inputbar form submitted
if( $_POST['inputbox'] ){
...
}
else{
echo "SETTING COOKIE: <br/><br/>";
// This print_r is only showing the $_COOKIE value (which is stored on $setting) on localhost but no on live server
print_r($setting);
switch( $com ){
...
}
}
?>
I've search about it everywhere (Google, stackoverflow, asking friends on twiiter/FB) still no solutions
I hope some body could give me the solution here
Thanks :)
Look at both path and domain parameters for the setcookie function.
Reference: setcookie # PHP docs http://php.net/manual/en/function.setcookie.php
Try this to set your cookie:
if ($on_localhost) { // change this
$domain = '.localhost';
} else {
$domain = '.webhoster.com'; // change this
}
setcookie(
'settings',
serialize($defaultSettings),
time()+3600*24*30,
'/', // this is the path
$domain // this is the domain
);
Good luck!
While applying solutions we get forgot the basic of Cookies.
Cookies are like headers. Like the headers, it should be sent before any output generates. then only it sets successfully. I have struggled a lot for this problem but when i went through the basics this problem got solved quickly.
this syntax will be enough to solve this problem...
setcookie(
'settings',
serialize($defaultSettings),
time()+3600*24*30,
'/' // this is the path
);
Try this:
setcookie("settings", serialize($defaultSettings), time()+3600*24*30, '/'); // added path
Also, could it be that serialize($defaultSettings) result is too large?
Try exit() after the Location-header.
A Location-header does not prevent a PHP-script from executing further instructions, maybe there is something executed after the header that causes the misbehaviour.
Probably your server time is not correct therefore Cookeis are not working on server.
Try this:
setcookie("settings", serialize($defaultSettings), 0);
Setting expiration to zero will fix your issue in this case. or update your server time.
Only initialize the ob_start() method before setcookie(). most of the developer ob_start() method include in config file.
OK, I'm stumped, and have been staring at this for hours.
I'm setting a cookie at /access/login.php with the following code:
setcookie('username', $username, time() + 604800, '/');
When I try to logout, which is located at /access/logout.php (and rewritten to /access/logout), the cookie won't seem to unset. I've tried the following:
setcookie('username', false, time()-3600, '/');
setcookie('username', '', time()-3600, '/');
setcookie('username', '', 1, '/');
I've also tried to directly hit /access/logout.php, but it's not working.
Nothing shows up in the php logs.
Any suggestions? I'm not sure if I'm missing something, or what's going on, but it's been hours of staring at this code and trying to debug.
How are you determining if it unset? Keep in mind that setcookie() won't remove it from the $_COOKIE superglobal of the current script, so if you call setcookie() to unset it and then immediatly print_r($_COOKIE);, it will still show up until you refresh the page.
Try pasting javascript:alert(document.cookie); in your browser to verify you don't have multiple cookies saved. Clear all cookies for the domain you're working on to make to sure you're starting fresh. Also ini_set(E_ALL); to make sure you're not missing any notices.
Seems to be a server issue. My last domain was pretty relaxed on PHP error handling while the new domain shows every error. I'm using both sites side by side and the old one removes the cookie as it should.
Is there perhaps a timezone issue here? Have you tried setting using something farther in the past, like time() - (3600*24)? PHP's documentation says that the internal implementation for deleting cookies uses a timestamp of one year in the past.
Also, you should be able to use just setcookie('username', false); without passing an expiration timestamp, since that argument is optional. Maybe including it is confusing PHP somehow?
How you use cookies data in your application?
If you read the cookies and check if username is not false or not '', then setting it to false or '' will be sufficient, since your application will ignore the cookies value.
You better put some security in cookies value, to prevent user change it's value. You can take a look of CodeIgniter session library, see how CI protect the cookies value using hash. Unauthorized value change will detected and the cookies will be deleted.
Also, CI do this to kill the cookies:
// Kill the cookie
setcookie(
$this->cookie_name,
addslashes(serialize(array())),
(time() - 31500000),
$this->cookie_path,
$this->cookie_domain,
0
);
You can delete cookies from javascript as well. Check here http://www.php.net/manual/en/function.setcookie.php#96599
A simple and convenient way, is to use this additional functions:
function getCookie($name) {
if (!isset($_COOKIE[$name])) return false;
if ($_COOKIE[$name]=='null') $_COOKIE[$name]=false;
return $_COOKIE[$name];
}
function removeCookie($name) {
unset($_COOKIE[$name]);
setcookie($name, "null");
}
removing a cookie is simple:
removeCookie('MyCookie');
....
echo getCookie('MyCookie');
I had a similar issue.
I found that, for whatever reason, echoing something out of logout.php made it actually delete the cookie:
echo '{}';
setcookie('username', '', time()-3600, '/');
I had the same issue; I log out (and I'm logged out), manually reload the index.php and then I'm logged in again. Then when I log out, I'm properly logged out.
The log out is a simple link (index.php?task=logout). The task removes the user from the session, and "deletes" (set value '' and set expiry in the past) the cookie, but index.php will read the user's auth token from the cookie just after this (or all) task (as with normal operations). Which will reload the user. After the page is loaded the browser will show no cookie for the auth token. So I suspect the cookie gets written after page finish loading.
My simple solution was to not read the cookie if the task was set to logout.
use sessions for authentication, don't use raw cookies
http://www.php.net/manual/en/book.session.php