HomeCoding & Programming

PHP: Difference between cookies and session

Like Tweet Pin it Share Share Email

What is the difference between cookies and session?

 

HTTP is a stateless protocol.
That mean, that treats each request as an independent transaction that is unrelated to any previous request. So, how about the request we want to make frequently, like username or id? As you know, we could store our data in COOKIE. When we store data in COOKIE, the browser will send the cookie data to server for each request. We already could use SESSION for this kind of task. So, what is difference between SESSION and COOKIE?

 

COOKIE
A cookie is a text-only string that takes a place in the memory of user’s browser. If the lifetime of the cookie is set to be longer than the time user spends at that site, then this string is saved to file for future reference. User could be disabled the cookie in their browser setting.

 

SESSION
A session is an object associated with a client connection to the server. it has the ability to carry information related to the client,session values are store in server side not in user’s machine. A session is available as long as the browser is opened. User couldn’t be disabled the session. We could store not only strings but also objects in session.

Session files are deleted automatically by php according to garbage collection settings.

 

1.The main difference between cookies and sessions is that cookies are stored in the user’s browser(hard disk), and sessions are not,cookies are browser dependent and sessions are not dependent on client’s browser settings

 

2.A cookie can keep information in the user’s browser until deleted. But Session work instead like a token allowing access and passing information while the user has their browser open.

 

3.The difference between sessions and cookies is that a session can hold multiple variables or objects, and you don’t have to set cookies for every variable. By default, the session data is stored in a cookie with an expiry date of zero, which means that the session only remains active as long as the browser. When you close the browser, all the stored information is lost. You can modify this behavior by changing the “session.cookie_lifetime” setting in “php.ini” from zero to whatever you want the cookie lifetime to be.

 

You can get the best! Once you know what each does, you can use a combination of cookies and sessions to make your site work exactly the way you want it to do.