Difference between setcookie() and session_set_cookie_params() functions
Solution 1
session_set_cookie_params(seconds)
session_start() does two things, it creates a temporary file on the server of which to store session data, and also sends a cookie to the user's browser. This cookie has a default expiration time, so calling session_set_cookie_params(seconds) will change the default expiration time of the cookie to what you define. The cookie basically points the client to their session so it is required to access the session.
Set Cookie()
where as setcookie() function defines a cookie to be sent along with the rest of the HTTP headers.
Solution 2
There are two types of cookies:
Session cookies : these are the session_set_cookie_params() and these are temporary cookie files, which are erased when you close your browser.
Persistent cookies : this is the setcookie() and these files stay in one of your browser's subfolders until you delete them manually or your browser deletes them based on the duration period contained within the persistent cookies.
For example if you want to have cookies to be saved for 1 week:
$remembering_timespan = time() + 7 * 24 * 60 * 60;
setcookie('test','username', $remembering_timespan);
Solution 3
Basically it's not the same.
For setcookie
<?php
$value = 'something from somewhere';
setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
?>
You could set like the above, the timeout session with the name and value itself. As for session_set_cookie_params:
session_set_cookie_params(
$currentCookieParams["lifetime"],
$currentCookieParams["path"],
$rootDomain,
$currentCookieParams["secure"],
$currentCookieParams["httponly"]
);
You can set the path , expiry of the cookie itself, the root domain , the secure level and many more parameter at here http://php.net/manual/en/function.session-set-cookie-params.php
The efficient way via PHP is below:
<?php
$currentCookieParams = session_get_cookie_params();
$rootDomain = '.example.com';
session_set_cookie_params(
$currentCookieParams["lifetime"],
$currentCookieParams["path"],
$rootDomain,
$currentCookieParams["secure"],
$currentCookieParams["httponly"]
);
session_name('mysessionname');
session_start();
setcookie($cookieName, $cookieValue, time() + 3600, '/', $rootDomain);
?>
The efficient coder ensure the parameter are to be set before setting the parameter itself so if the user is off grid. There's expiry on the cookie itself.
Related videos on Youtube
EternalSunShine
Updated on September 16, 2022Comments
-
EternalSunShine over 1 year
I am trying to understand the difference between PHP functions setcookie() and session_set_cookie_params().
Looks like both functions are doing the same kind of tasks but setcookie() can be used to create cookie with name & value.
I tried to understand PHP manuals but no clear differences pointed out in it.
Thanks