difference between cookie and session in PHP

Both cookies and sessions are available in any type of programming language like PHP, and both accomplish much the same task of storing data across pages on your site. However, there are differences between the two that will make each favourable in their own circumstance.

Sessions are stored on the server, which means clients do not have access to the information you store about them – this is particularly important if you store shopping baskets or other information you do not want you visitors to be able to edit by hand by hacking their cookies. Session data, being stored on your server, does not need to be transmitted with each page; clients just need to send an ID and the data is loaded from the local file.

sessions can be any size because they are held on your server, whereas cookie size is depend on browser because many web browsers have a limit on how big cookies can be to stop rogue web sites chewing up gigabytes of data with meaningless cookie information.

Scenarios:
1. Do you want your data to work when you visitor comes back the next day? If so, then your only choice is cookies –
2. if you have any particularly sensitive information, your best bet is to store it in a database, then use the cookie to store an ID number to reference the data.
3. If you do not need semi-permanent data, then sessions are generally preferred, as they are a little easier to use, do not require their data to be sent in entirety with each page, and are also cleaned up as soon as your visitor closes their web browser.

Difference between cookie and session in PHP is a common question asked in interview.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.