Gautam Kumar
Gautam Kumar

Reputation: 1170

php sessions and cookies

When should we use session and cookies in PHP? Please specify separately their uses,pros and cons.

Upvotes: 2

Views: 419

Answers (4)

Babiker
Babiker

Reputation: 18818

Use sessions for sensitive information like log in credentials and such. sessions are stored in the server, usually the /tmp directory. Cookies can be viewed and modified by the user because they are client side. Its never a good idea to build your app based on cookies as a dependency, because browsers can be set to reject cookies. aaaaaaaand there goes your app.

Upvotes: 1

Galen
Galen

Reputation: 30170

Sessions are cookies. The difference is sessions store a session id in the cookie and nothing else. Cookies, if youre not careful, can store sensitive data. Either way you should be careful, but to me stealing data from a session system is more involved than stealing data from a cookie.

The only reason i can see to use cookies and not sessions is if you need the data to persist longer than one browser opening. For instance a "keep me logged in" feature. Otherwise use sessions.

Upvotes: 1

selfawaresoup
selfawaresoup

Reputation: 15832

Well, explaining it "separately" will be difficult since cookies are mostly used to store a session identifier on the clients machine. This is done by PHP automatically as soon as you start session (can be configured differently).

The session is then used to identify and recognize the user and to pass information from one request to the next that the user must not be allowed to modify (session data is stored on the server).

Cookies can also be used to store data on the clients machine that is not security related and that can be used to remember a certain state on the page for the user for example.

Just remember: Cookies can be easily manipulated. Use Session for everything that is security related.

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157991

Cookies are long term and stored data is unsafe, because stored on the client side
Sessions are short term, virtually "until user closes his browser" and stored data considered to be safe, because stored on the server side
that's all

Upvotes: 2

Related Questions