What is the difference between Session and Cookie?

A “session” is set for maintaining the user data as the person is browsing through the site. A session is very useful in e-commerce websites, social networking sites etc. In PHP, session variables are used to set the sessions. Anything can be set / stored in a session like the user’s id, username, some encrypted password string etc.

A session is always stored in the server. You lose all the session data once you close your browser, as every time you re-open your browser, a new session starts for any website.

Example: $_SESSION[‘customer_name’] = ‘John’;
PHP Questions
A “cookie” is however different from a session. It stores some information like the username, last visited pages etc. So that when the customer visits the site again, he may have the same environment set for him. You can store almost anything in a browser cookie.

A cookie is stored in the client’s browser.

Like, when you check the ‘Remember Password’ link on any website, a cookie is set in your browser, which exists there in the browser until manually deleted. So, when you visit the same website again, you don’t have to re-login.

But, it can also be problematic at times, if the user has blocked cookies in his browser and you have a shopping site that utilizes cookies to store the data. Then, that person will never be able to shop from your website.

Example:

setcookie("username", "John", time()+2400);

Leave a Reply

Your email address will not be published. Required fields are marked *