Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between setcookie() and session_set_cookie_params() functions

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

like image 287
EternalSunShine Avatar asked Feb 22 '17 07:02

EternalSunShine


People also ask

What is Setcookie () function?

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.

What is Session_set_cookie_params?

The session_set_cookie_params() is used to set the session cookie parameters defined in the php.ini file.

At what point in a PHP file should the Setcookie () function be called?

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.


2 Answers

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.

like image 77
Saquib Lari Avatar answered Sep 30 '22 23:09

Saquib Lari


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);
like image 44
nrii Avatar answered Sep 30 '22 21:09

nrii