PHP Setting HTTP Cookie - php

I want to add a cookie using PHP to the browser which the expiration date is one year after the cookie is set. I have set the variable name,value,path "/",domain and the expiry date. However, when I close the browser and open the website again using the same browser, no cookies are sent to the web page. What happened? The cookie is still applicable if I only close the window only. Yet things happened when the application is shut down and opened again.
setcookie("LANG","english",time()+365*60*60*24,"/","sub.domain.org");

This is how to set the cookie:
$expire=time()+60*60*24*365;
setcookie("name", value, $expire);
to bring to cookie again:
$_COOKIE['name']

Related

Destroy cookie when browser window closes PHP

I have created a popup in WordPress that will open when visitor IP is from Australia. The popup will show up on page load. I want to make it not show until the browser screen is closed.
For this, I used the cookie. I set the cookie when the close button is clicked and creating the cookie in PHP using ajax.
Here is the code I am using to create cookie:
setcookie("stay_here", "yes", 0, "/");
I set the cookie time to 0 so that it will destroy when the browser closed. The issue is that the site has user account area and when the user is logged in the session of the user is created. This session is not destroying after closing the browser. And when the above cookie created it automatically set expiration time as "Session".
I checked this on firefox and the data variable "Expires" of the cookie is set as "Session". As the session is not destroying when I close the browser and the cookie Expires value which is set as Session is also not destroying.
But I want the only cookie to be destroyed when the browser is closed not the Session.
I hope you understand my issue.
Can you guys look at the issue and provide me a solution to achieve this situation.
Thanks in Advance.
Ideally cookie created through SETCOOKIE function in PHP with its expire time 0, it will be deleted from browser when you will close the tab and time can't be overwrite with session's cookie time.
Try to create 1 test.php page and write setcookie("stay_here", "yes", 0, "/"); code and check from browser's cookie information.
You can also, set session cookie's time to 0 so session cookie will also deleted when browser will be closed.
ini_set('session.cookie_lifetime', 0);
See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
It states under "Session cookies":
However, web browsers may use session restoring, which makes most
session cookies permanent, as if the browser was never closed.
In short: There is no reliable way to detect if a browser was closed.
What you can do is make a cookie that will expire in 12 hours:
setcookie("last_page_hit",$PHP_SELF,time()+12*60*60,"/");
if that cookie is absent you assume it is a new visit to the site and you show the popup again.
assuming your rm cookie is set and you are viewing page on header.php, you can refresh and update the cookie state.
if (isset($_COOKIE['rm']) || (isset($rm) && $rm)) {
ini_set('session.gc_maxlifetime', $lifetime);
ini_set('session.cookie_lifetime', $lifetime);
}
You can use sessionStorage https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
It will store on clients side until window is closed.
It's relatively new feature, so you should check if it's supported by your clients browsers.

php session cookie not gone after closing browser

Book said, persistent cookie stay on client machine till it expires.
session cookie will be gone after browser closed.
i tried it, like:
setcookie("name", "value"); // before any output
but after closing browser and restart, it is still there
(from print_r($_COOKIE)).
i tried couple of different browsers like safari, chrome, firefox,
it is all like that. only eclipse is different:)
so, are all current browsers not following that "rule" ?
or there is some default time-out for a session cookie i am
not aware of?
thanks.
EDIT:
I checked in firebug it said:
Name Value Domain Expires
name value localhost session
Check your PHP settings for session cookie name, domain and path, and unset the cookie using the same values given to setcookie(). They can all be read with ini_get() and fed to variables.
The above advice assumes you're using PHP built-in session mechanism, ie. you don't use a framework with it's own, custom session library.
What you set there is not a session cookie. After the page is loaded in the browser go check the cookies set from your server (localhost if it's local machine), you'll see a SESS_ID cookie which is set by the server and it goes when you close the browser
What you are actually trying to set is a persistent cookie..A session cookie or simply session can be simply set by starting a session or storing a value in session like $_SESSION['name']=$value.
What you are doing is a persistent cookie it wont expire even if browser is closed. It expires only after the time set in cookie expires.
Like setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); it will set cookie info for 1 day..even if browser it closed..
You can set time and cookie info according to your needs...
`
That's because you're setting a cookie.
Sessions are not cookies. Cookies are not sessions.
http://www.tuxradar.com/practicalphp/10/1/0
Quoted from the first page:
Cookies can be set to a long lifespan, which means that data stored in a cookie can be stored for months if not years.
And sessions, via the page on sessions:
It is also important to note that sessions only last till the user closes their browser, whereas cookies can be configured to last longer.
Thanks to everyone's response. It's my problem.
i am working on macbook, i thought clicking the red cross will close
the browser. but although browser is gone. on the very top of my screen,
it is still safari menu bar. i have to click safari and quit it.
now, all my session cookies are gone after closing the browser:)

When does a PHP session end?

I can't seem to find a definitive answer on the internet, so I'm asking here.
When one uses session_start(); in a .php script and saves some values, when does the session end? So when would those values not be accessible again?
I've found that refreshing the page or stopping the session code-wise would stop it, and a possible time-out would stop the session as well. But what about navigating away from the site and returning a minute later? And closing the browser?
As for the last one, on mobile, what does 'closing the browser' mean? Closing the tab or even minimalising the site?
If your session values are not linked to any cookie, the session will end when the windows browser will be closed.
If your session variable comes from a cookie, the session will end after time specified in the cookie file.
In PHP, sessions work with a cookie of type session. Server-side, the session information is constantly deleted.
To set the lifetime of a cookie in php, you can use the function session_set_cookie_params, before the session_start:
session_set_cookie_params(3600,"/");
session_start();
For ex, 3600 seconds is a one hour, for 2 hours 3600*2 = 7200.
But it's a session cookie, the browser can make it expire by himself, if you want to save longer sessions (like remember login), you need save the data in the server and a standard cookie on the client side.
Navigating away from a site when using cookies will not break the session.
There are two things that can effectively end a session:
The cookie linking it to the browser gets destroyed. PHP typically uses session cookies. These are deleted when the browser is closed. The browser, not the tab. They can also be deleted manually.
When the server hasn't received a request from the browser with the session cookie for the session for a certain amount of time (defined in session.gc_maxlifetime) and it cleans up the session data.

PHP - Session is set after browser restart, but PHP acts as isn't

I've seen various questions like mine, though none provide the correct answer.
I've a PHP script:
session_start();
setcookie(session_name('DSWLogin'),session_id(),time()+2*7*24*60*60, '/');
//This will only be set once (when the user logs in)
$_SESSION['test'] = 'Yup, I am working';
if (isset($_SESSION['test'])){
echo 'Session is set and ready!';
} else {
echo 'No session was set...';
}
and that all works fine except after a browser restart, my PHP script ignores the session.
When my browser hasn't restarted yet, it'll echo 'Session is set and ready!'; just fine.
And when I look into my cookie tab, it indeed says a cookie, named DSWLogin has been set with a certain value.
When I restart my browser, my cookie tab still says that a cookie, named DSWLogin has been set with the same value it had before the restart, so it is still there!
But my PHP script apparently ignores is, and outputs 'No session was set...'...
Thanks in advance,
Isaiah v. Hunen
What you are trying to do is not really the correct way to achieve this. Sessions have two parts, a cookie with a session id set by default to expire at the end of the session (usually browser close) and a server side storage mechanism that is cleaned up automatically after a certain period of time after the last request was received.
What you are trying to do is extend the session to two weeks. While you could change the cookie settings and increase the timeout to session garbage collection doing this is not very reliable.
Instead you want to look at using a one time key stored in a cookie which acts as an alternate login path. This cookie can recreate the session just like a normal login would. There are some details that need to be considered for this to remain secure, but it will do what you are attempting to achieve.
Just because you are setting your session_id in some cookie doesn't mean it is THE session cookie. Most browsers will purge session cookies on browser close. This is what you are seeing. Look at the cookies in your browser that are set when your session is valid and compare this to the cookies that are still remaining after browser restart. You will notice your true session cookie has gone missing.
Quoting the manual:
The session name is reset to the default value stored in session.name
at request startup time. Thus, you need to call session_name() for
every request (and before session_start() or session_register() are
called).
Also if you want to change lifetime of session cookie, use session_set_cookie_params instead of forcing your own cookie.
Also read about session garbage collection and configuration, changing cookie lifetime might not be enough.

How to destroy or unset or similar the PHP session in Chrome when browser closes if Chrome doesn't do it automatically?

I'm using a PHP session for a website to display a disclaimer page when the user first logs on to the site. After the user's browsing session, or when they close their browser, the session should be destroyed automatically. It is working properly in all browsers except for Chrome. After some research, I found this which led to this. If it is indeed a bug with Chrome, how can I work around it?
Session cookies are suppose to be deleted if browser being closed and they are sent without expire time.
You can define session_cache_expire before start session first time:
session_cache_expire(60); // expires after 60 mins
And then do session_start();...
Instead of relying on the browser to cancel the cookie, set it to expire fairly quickly, and keep the session "alive" by renewing the cookie on subsequent page requests.
<?php
session_set_cookie( 60*15 );
session_start();
This example sets the cookie to expire after 15 minutes (you might set a different expiry, depending on how often you expect your users to send page requests: or, you could set it for only a minute or two, and get a fresh cookie via XHR just a little more frequently than that). This won't make Chrome delete the cookie, but you at least know it won't be floating around indefinitely.

Categories