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
The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers. A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.
The session_set_cookie_params() is used to set the session cookie parameters defined in the php.ini file.
A cookie can be set or modified using the following syntax: setcookie(name, value, expire, path, domain, secure, httponly); Note that: Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With