Cookies vs. sessions in PHP - php

I started using PHP a couple of months ago. For the sake of creating a login system for my website, I read about cookies and sessions and their differences (cookies are stored in the user's browser and sessions on the server).
At that time, I preferred cookies (and who does not like cookies?!) and just said: "who cares? I don't have any good deal with storing it in my server", so, I went ahead and used cookies for my bachelor graduation project.
However, after doing the big part of my app, I heard that for the particular case of storing user's ID, sessions are more appropriate. So I started thinking about what would I say if the jury asks me why have you used cookies instead of sessions? I have just that reason (that I do not need to store internally information about the user). Is that enough as a reason? or it's more than that?
Could you please tell me about advantages/disadvantages of using cookies for keeping User's ID?

The concept is storing persistent data across page loads for a web visitor. Cookies store it directly on the client. Sessions use a cookie as a key of sorts, to associate with the data that is stored on the server side.
It is preferred to use sessions because the actual values are hidden from the client, and you control when the data expires and becomes invalid. If it was all based on cookies, a user (or hacker) could manipulate their cookie data and then play requests to your site.
Edit: I don't think there is any advantage to using cookies, other than simplicity. Look at it this way... Does the user have any reason to know their ID#? Typically I would say no, the user has no need for this information. Giving out information should be limited on a need to know basis. What if the user changes his cookie to have a different ID, how will your application respond? It's a security risk.
Before sessions were all the rage, I basically had my own implementation. I stored a unique cookie value on the client, and stored my persistent data in the database along with that cookie value. Then on page requests I matched up those values and had my persistent data without letting the client control what that was.

Basic ideas to distinguish between those two.
Session:
UID is stored on server (i.e. server-side)
Safer (because of 1)
Expiration can not be set, session variables will be expired when users close the browser. (nowadays it is stored for 24 minutes as default in php)
Cookies:
UID is stored on web-browser (i.e. client-side)
Not very safe, since hackers can reach and get your information (because of 1)
Expiration can be set (see setcookies() for more information)
Session is preferred when you need to store short-term information/values, such as variables for calculating, measuring, querying etc.
Cookies is preferred when you need to store long-term information/values, such as user's account (so that even when they shutdown the computer for 2 days, their account will still be logged in). I can't think of many examples for cookies since it isn't adopted in most of the situations.

SESSIONS ENDS WHEN USER CLOSES THEIR BROWSER,
COOKIES END DEPENDING ON THE LIFETIME YOU SET FOR IT. SO THEY CAN LAST FOR YEARS
This is the major difference in your choice,
If you want the id to be remembered for long time, then you need to use cookies; otherwise if you just want the website to recognize the user for this visit only then sessions is the way to go.
Sessions are stored in a file your php server will generate. To remember which file is for which user, php will also set a cookie on the user's browser that holds this session file id so in their next visit php will read this file and reload the session.
Now php by default clears sessions every interval, and also naming convention of session make it auto expire. Also, browsers will not keep the cookie that holds the session id once the browser is closed or the history is cleared.
It's important to note that nowadays browsers also support another kind of storage engines such as LocalStorage, SessionStorage, and other webdb engines that javascript code can use to save data to your computer to remember you. If you open the javascript console inside Facebook, for example, and type "localStorage" you will see all the variables Facebook uses to remember you without cookies.

Short answer
Rules ordered by priority:
Rule 1. Never trust user input : cookies are not safe. Use sessions for sensitive data.
Rule 2. If persistent data must remain when the user closes the browser, use cookies.
Rule 3. If persistent data does not have to remain when the user closes the browser, use sessions.
Rule 4. Read the detailed answer!
Source : https://www.lucidar.me/en/web-dev/sessions-or-cookies/
Detailed answer
Cookies
Cookies are stored on the client side (in the visitor's browser).
Cookies are not safe: it's quite easy to read and write cookie contents.
When using cookies, you have to notify visitors according to european laws (GDPR).
Expiration can be set, but user or browser can change it.
Users (or browser) can (be set to) decline the use of cookies.
Sessions
Sessions are stored on the server side.
Sessions use cookies (see below).
Sessions are safer than cookies, but not invulnarable.
Expiration is set in server configuration (php.ini for example).
Default expiration time is 24 minutes or when the browser is closed.
Expiration is reset when the user refreshes or loads a new page.
Users (or browser) can (be set to) decline the use of cookies, therefore sessions.
Legally, you also have to notify visitors for the cookie, but the lack of precedent is not clear yet.
The appropriate choice
Sessions use a cookie! Session data is stored on the server side, but a UID is stored on client side in a cookie. It allows the server to match a given user with the right session data. UID is protected and hard to hack, but not invulnarable. For sensitive actions (changing email or resetting password), do not rely on sessions neither cookies : ask for the user password to confirm the action.
Sensitive data should never be stored in cookies (emails, encrypted passwords, personal data ...). Keep in mind the data are stored on a foreign computer, and if the computer is not private (classroom or public computers) someone else can potentially read the cookies content.
Remember-me data must be stored in cookies, otherwise data will be lost when the user closes the browser. However, don't save password or user personal data in the 'remember-me' cookie. Store user data in database and link this data with an encrypted pair of ID / key stored in a cookie.
After considering the previous recommandations, the following question is finally what helps you choosing between cookies and sessions:
Must persistent data remain when the user closes the browser ?
If the answer is yes, use cookies.
If the answer is no, use sessions.

when you save the #ID as the cookie to recognize logged in users, you actually are showing data to users that is not related to them. In addition, if a third party tries to set random IDs as cookie data in their browser, they will be able to convince the server that they are a user while they actually are not. That's a lack of security.
You have used cookies, and as you said you have already completed most of the project. besides cookie has the privilege of remaining for a long time, while sessions end more quickly. So sessions are not suitable in this case. In reality many famous and popular websites and services use cookie and you can stay logged-in for a long time. But how can you use their method to create a safer log-in process?
here's the idea: you can help the way you use cookies: If you use random keys instead of IDs to recognize logged-in users, first, you don't leak your primary data to random users, and second, If you consider the Random key large enough, It will be harder for anyone to guess a key or create a random one. for example you can save a 40 length key like this in User's browser:
"KUYTYRFU7987gJHFJ543JHBJHCF5645UYTUYJH54657jguthfn"
and it will be less likely for anyone to create the exact key and pretend to be someone else.

Actually, session and cookies are not always separate things. Often, but not always, session uses cookies.
There are some good answers to your question in these other questions here. Since your question is specifically about saving the user's IDU (or ID), I don't think it is quite a duplicate of those other questions, but their answers should help you.
cookies vs session
Cache VS Session VS cookies?
What is the difference between a Session and a Cookie?

TL;DR
Criteria / factors
Sessions
Cookies
Epoch (start of existence)
Created BEFORE an HTTP response
Created AFTER an HTTP response
Availability during the first HTTP request
YES
NO
Availability during the succeeding HTTP requests
YES
YES
Ultimate control for the data and expiration
Server administrator
End-user
Default expiration
Expires earlier than cookies
Lasts longer than sessions
Server costs
Memory
Memory
Network costs
None
Unnecessary extra bytes
Browser costs
None
Memory
Security
Difficult to hijack
Easy to hijack
Deprecation
None
Now discouraged in favor of the JavaScript "Web Storage"
Details
Advantages and disadvantages are subjective. They can result in a dichotomy (an advantage for some, but considered disadvantage for others). Instead, I laid out above the factors that can help you decide which one to pick.
Existence during the first HTTP request-and-response
Let's just say you are a server-side person who wants to process both the session and cookie. The first HTTP handshake will go like so:
Browser prepares the HTTP request -- SESSIONS: not available; COOKIES: not available
Browser sends the HTTP request
Server receives the HTTP request
Server processes the HTTP request -- SESSIONS: existed; COOKIES: cast
Server sends the HTTP response
Browser receives the HTTP response
Browser processes the HTTP response -- SESSIONS: not available; COOKIES: existed
In step 1, the browser have no idea of the contents of both sessions and cookies.
In step 4, the server can have the opportunity to set the values of the session and cookies.
Availability during the succeeding HTTP requests-and-responses
Browser prepares the HTTP request -- SESSIONS: not available; COOKIES: available
Browser sends the HTTP request
Server receives the HTTP request
Server processes the HTTP request -- SESSIONS: available; COOKIES: available
Server sends the HTTP response
Browser receives the HTTP response
Browser processes the HTTP response -- SESSIONS: not available; COOKIES: available
Payload
Let's say in a single web page you are loading 20 resources hosted by example.com, those 20 resources will carry extra bytes of information about the cookies. Even if it's just a resource request for CSS or a JPG image, it would still carry cookies in their headers on the way to the server. Should an HTTP request to a JPG resource carry a bunch of unnecessary cookies?
Deprecation
There is no replacement for sessions. For cookies, there are many other options in storing data in the browser rather than the old school cookies.
Storing of user data
Session is safer for storing user data because it can not be modified by the end-user and can only be set on the server-side. Cookies on the other hand can be hijacked because they are just stored on the browser.

I personally use both cookies and session.
Cookies only used when user click on "remember me" checkbox. and also cookies are encrypted and data only decrypt on the server. If anyone tries to edit cookies our decrypter able to detect it and refuse the request.
I have seen so many sites where login info are stored in cookies, anyone can just simply change the user's id and username in cookies to access anyone account.
Thanks,

Sessions allow you to store away individual pieces of information just like with cookies, but the data gets stored on the server instead of the client.

Session and Cookie are not a same.
A session is used to store the information from the web pages. Normally web pages don’t have any memories to store these information. But using we can save the necessary information.
But Cookie is used to identifying the users. Using cookie we can store the data’s. It is a small part of data which will store in user web browser. So whenever user browse next time browser send back the cookie data information to server for getting the previous activities.
Credits : Session and Cookie

I will select Session, first of all session is more secure then cookies, cookies is client site data and session is server site data.
Cookies is used to identify a user, because it is small pieces of code that is embedded my server with user computer browser. On the other hand Session help you to secure you identity because web server don’t know who you are because HTTP address changes the state 192.168.0.1 to 765487cf34ert8ded…..or something else numbers with the help of GET and POST methods. Session stores data of user in unique ID session that even user ID can’t match with each other. Session stores single user information in all pages of one application.
Cookies expire is set with the help of setcookies() whereas session expire is not set it is expire when user turn off browsers.

Cookies and Sessions are used to store information. Cookies are only stored on the client-side machine, while sessions get stored on the client as well as a server.
Session
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
A session ends when the user closes the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.
Cookies
Cookies are text files stored on the client computer and they are kept of use tracking purposes. The server script sends a set of cookies to the browser. For example name, age, or identification number, etc. The browser stores this information on a local machine for future use.
When the next time the browser sends any request to the web server then it sends those cookies information to the server and the server uses that information to identify the user.

As others said, Sessions are clever and has more advantage of hiding the information from the client.
But Cookie still has at least one advantage, you can access your Cookies from Javascript(For example ngCookies). With PHP session you can't access it anywhere outside PHP script.

A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session. save _ path location and actually "see sessions".
A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.

See the illustration to compare differences b/w Cookies and Session.

Related

Security questions from login with SESSIONS (PHPSESSID) or COOKIES if is same.. or not?

I have several questions about SESSIONS and COOKIES, I read in internet and all people recommend use SESSIONS (for security) but.. Not is same save the ID login in one session (phpsessid) that save in one cookie?
I tested this:
I copied my PHPSESSID ID (cookie) from my login account from a website
( in chrome) and insert my PHPSESSID (cookie) in another browser (in
opera) with VPN and I can access in this account.
What is the security here? if anyone can guess or hijack my cookie PHPSESSID ID is same if I use a Cookie to saving the login id, or not?
My question is.. Dont is more secure use a secure cookie ID like in wordpress, encrypting ID and checking in DB the IP and USER_AGENT ?
Now, I using this:
I create a random ID and save in one cookie (when the user login is success)
And check if this ID exist in the DB, check if the IP (saved in DB) and USER_AGENT (saved in DB) is equal. if not, login another time
Anyone can me guide a little? Thx you for read.
You should ask yourself this: "How easy is it to guess the randomly generated random id?".
If your answer to this question is "very easy" you should make it harder to guess. Use a UUID or some other form of securely random ID.
If you answer is "quite hard" you should not have to worry about this. The only attack vector you are offering is to be able to guess a randomly generated id.
You can read more about "guessing the PHPSESSID" here.
In general it should not be necessary to check the IPs of the user (as a side note, you open up yourself to all the stuff in the GDPR by doing this) or their User-Agent as both things might change during the sessions lifetime.
The key point about sessions is that they are a server-side storage. In other words, your program writes whatever it sees fit and it reads back exactly what it wrote before because information cannot be tampered by clients as it happens with cookies. Additionally, the information remains hidden to client's eyes so it can store confidential or just internal uninteresting information. Last but not least, a PHP session allows to store most data types supported by PHP. A cookie can only store plain text.
The weak link in sessions is that HTTP is a stateless protocol so the client needs to identify itself on every request (unlike it happens in other network protocols as FTP, SSH or SMTP). Earlier implementations would transmit the session ID in the URL itself. It was later improved to only use cookies and cookies can be configured to be restricted to encrypted connections. But, yes, if something intercepts your HTTP traffic and finds out your session ID he can easily impersonate you because most sites don't care about implementing further checks. However, that's why HTTPS is encouraged nowadays.

php checking session secure enough?

I have two possibly elementary questions about php SESSIONs and cookies
1) How does the server know when a session terminates? Or when to get rid of the session_id and info etc. (that is, if session_destroy isn't called)
2) Being that on the client side a cookie is stored containing a unique session id that the server uses to identify the individual, if someone were to gain access to that session id they could access all of the same information right? Is there an extra level of security necessary then to identify a user other than simply checking the session information?
How does the server know when a session terminates?
Session is basically a bunch of data, stored on the server. The client is recognized and matched to a specific session by the session ID, stored in the session and on the client side in a cookie with the default name of PHPSESSID. (You can find its value in your browser or using session_id() function in PHP.) If the browser deletes this cookie, the session ID is lost on the client side, and there is no way the client can get back other data stored in the session on the server. This data is eventually deleted by the garbage collector.
The garbage collector is called with some probability each time when session_start() is called. The probability equals to gc_probability/gc_divisor. Garbage collector deletes the session data if the session was around for more than gc_maxlifetime seconds. You can check all these values in phpinfo() output or using e.g. ini_get('session.gc_maxlifetime'). That's about the session data on the server. Now about the client.
Session configuration contains a value session.cookie_lifetime. Quoting PHP manual:
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0.
From PHP Sessions and security:
0 have special meaning. It tells browsers not to store cookie to permanent storage. Therefore, when browser is terminated, session ID cookie is deleted immediately. If developer set other than 0, it may allow other users to use the session ID. Most applications should use "0" for this. If auto login feature is required, implement your own secure auto login feature. Do not use session ID for it.
You can check the setting using any of the following:
phpinfo(), look for session.cookie_lifetime in the session section.
session_get_cookie_params()['lifetime']
ini_get('session.cookie_lifetime')
So basically, if the session cookie lifetime is 0, the browser deletes it when it is closed and the client loses access to the session data.
If someone were to gain access to that session ID, they could access all of the same information?
Yes. As long as the ID is known to (any) client and the session data is not deleted on the server, the client can access it.
Is there an extra level of security necessary then to identify a user other than simply checking the session information?
It depends on your application. Getting the session ID is not trivial, one needs either to intercept the communication or have direct access to the client data. Interception can be prevented using TLS-based encrypted connection. Getting the client data requires some malicious software.
This article describes a safer cookie implementation for user authentication. In short, while it still doesn't prevent cookie hijacking, it gives you a way to detect it, notify the user and prevent the stolen cookie from being re-used.
Another article lists gives a more complete overview of good practices for user authentication. As usual, security requires that the whole project is implemented in a secure way, not just one, seemingly critical part of it. But if my suggest, don't overdo it. The effort should be reasonable for the particular requirements of each project.

What is a proper way to create a secure login procedure? [duplicate]

This question already has answers here:
Creating a secure login using sessions and cookies in PHP
(5 answers)
Closed 9 years ago.
I would like to know what would be a proper way to create a login procedure.
Up to this point I thought it would be a good way to create a $_SESSION['login'] and even a $_COOKIE['login'] that both have the same content which is a kind of a timestamp plus an encrypted form of the password.
The logic behind that idea is to check if both exist and to compare their contents. If both exist and is the content equal you get access to the protected pages.
I do know that a Cookie is a kind of a Session. A Cookie will be stored on the users client site and the a Session as well but will last only as long as the browser will be open. I thought it would be possible to extend the lifetime of a Session even when the browser will be closed and the Session destroyed.
This should ensure that the SESSION could not be hacked and the COOKIE be stolen what makes it impossible for a hacker to get access to a profile of an User.
Am I right with that thoughts or how do you people did it?
Thanks alot.
First off you need to understand the difference between sessions and cookies.
Sessions and cookies are both key=>value stores. But where they're stored has great impact on their security properties.
Cookies are stored on the client machine. They are unsafe. A user can modify the value of a cookie, forget a cookie, send more cookies etc. Cookies can be stored for a very long period of time (months, years). Since the client stores the cookie you don't need to worry too much about space constraints. Just keep in mind that all the cookies are sent with every request.
Things you store in cookies are typically fairly inconsequential things like some preference settings or "I've already seen your popup asking me about questionnaire".
Session data is stored on the server, only the server can read from it and write to it. The user never sees what is in the session. Session data typically expires quickly, let's say anywhere between 30 minutes and 24 hours.
But how do you know which session belongs to which visitor? Well, you use a session identifier cookie. This is the only cookie you need for authentication. In PHP this cookie is PHPSESSID and it's created and used automatically when you call session_start();. The session cookie is a cookie with a random value that is hard to 'guess', which makes it secure.
The user will keep the session cookie. You can find the associated session data (automatically using $_SESSION). In the session data you can store whether the user is logged in, if so as which user, you can even store the rights a user has (like a mini-cache). You can treat this as an untamperable key=>value store, just make sure not to store too much in there (the limits depend on the storage mechanism).
Sessions are stored in a specific place; where depends on your webserver and OS. In PHP you can specify your own session storage handler by calling session_set_save_handler. This allows you to, for instance, keep your session data in a database.
If the value of the session identifier cookie is somehow exposed an attacker can hijack the session. It can be exposed by using an unsecured connection on a wifi access point (like in a bar). To counter this use HTTPS; cookies sent over HTTPS are encrypted and safe from this kind of man-in-the-middle attack. This is what the Firesheep plugin did (in 2010)

How exactly does session hijacking work in PHP?

I've made a website which has registration/login. I can see the PHPSESSID cookie in Chrome's Developer Tools, so I'm wondering how can I use this session id value to hijack into the account I'm logged, from let's say a different browser, for simplicity's sake?
Should a secure website be able to determine that this session is being hijacked and prevent it?
Also, how come other big sites that use PHP (e.g. Facebook) do not have PHPSESSID cookies? Do they give it a different name for obscurity, or do they just use a different mechanism altogether?
Lots of good questions, and good on you for asking them.
First.. a session is just a cookie. A 'session' is not something that's part of the HTTP stack. PHP just happens to provide some conveniences that make it easy to work with cookies, thus introducing sessions. PHP chooses PHPSESSID as a default name for the cookie, but you can choose any you want.. even in PHP you can change the session_name.
Everything an attacker has to do is grab that session cookie you're looking at, and use it in its own browser. The attacker can do this with automated scripts or for instance using firebug, you can just change the current cookie values.
So yes, if I have your id.. I can steal your session if you didn't do anything to prevent it.
However.. the hardest part for an attacker is to obtain the cookie in the first place. The attacker can't really do this, unless:
They have access to your computer
They somehow are able to snoop in on your network traffic.
The first part is hard to solve.. there are some tricks you can do to identify the computer that started the session (check if the user agent changed, check if the ip address changed), but non are waterproof or not so great solutions.
You can fix the second by ensuring that all your traffic is encrypted using HTTPS. There are very little reasons to not use HTTPS. If you have a 'logged in' area on your site, do use SSL!!
I hope this kind of answers your question.. A few other pointers I thought of right now:
Whenever a user logs in, give them a new session id
Whenever a user logs out, also give them a new session id!
Make sure that under no circumstances the browser can determine the value of the session cookie. If you don't recognize the cookie, regenerate a new one!
If you're on the same IP and using the same browser, all you have to do is duplicating the session ID (and maybe other cookie values: not really sure if browser specific things like its agent string is tracked/compared; this is implementation dependant).
In general, there are different ways to track users (in the end it's just user tracking). For example, you could use a cookie or some hidden value inside the web page. You could as well use a value in HTTP GET requests, a Flash cookie or some other method of authentication (or a combination of these).
In case of Facebook they use several cookie values, so I'd just assume they use one of these values (e.g. 'xs').
Overall, there's no real 100% secure way to do it (e.g. due to man-in-the-middle attacks), but overall, I'd do the following:
Upon logging in, store the user's IP address, his browser agent string and a unique token (edit due to comment above: you could as well skip he IP address; making the whole thing a bit less secure).
Client side store the user's unique id (e.g. user id) and that token (in a cookie or GET value).
As long as the data stored in first step matches, it's the same user. To log out, simply delete the token from the database.
Oh, and just to mention it: All these things aren't PHP specific. They can be done with any server side language (Perl, PHP, Ruby, C#, ...) or server in general.
Someone sniffs the session ID cookie and sets it for a subsequent request. If that's the only thing authenticated a user, they're logged in.
Most sites will use authentication based on cookies in some form. There are several ways to make this more secure such as storing info about the user's browser when they log in (e.g. user agent, IP address). If someone else naively tries to copy the cookie, it won't work. (Of course, there are ways around this too.) You'll also see session cookies being regenerated periodically to make sure they aren't valid for a particularly long time.
Check out Firesheep for a Firefox extension that performs session hijacking. I'm not suggesting you use it, but you may find the discussion on that page interesting.

Purpose Of PHP Sessions and Cookies and Their Differences

I am just starting to learn to program in PHP and have ran into a slightly confusing area, Sessions and Cookies.
I understand the server-side and client-side storage differences but i cant see how they differentiate and in what circumstances would each be appropriate for?
Also, i have seen people say that the cookie could be used to store a session id, How would this be done and why would this be advantageous?
Thanks for any feedback.
First of all, let's bust the longstanding myth (or at least I think it's an existing myth) that a session cookie is something different than a regular cookie. It is not. A session cookie is just a regular cookie. Only the properties of the session cookie that are set (or rather not set) are typically different. But the mechanism is exactly the same.
A cookie is set by sending a http response header to the browser:
Set-Cookie: name=value[; possible expiration-date][; other possible properties]
What typically distinguishes a session-cookie from a regular cookie is that no expiration date is set (or the expiration date is set to a date in the past). Which means the browser will dispose the cookie after closing the browser. But a 'regular' cookie can do this just as well. Thus thereby making it a 'session cookie' so to speak.
Now that we have that out of the way; the mechanism by which cookies are typically utilized by applications to make them act as even more of a session cookie, besides above mentioned properties, is that the value of the cookie only holds a uniquely identifiable value of some sort. Perhaps an md5 of maybe a sha1 hash.
Each time the browser requests a resource on the server it sends along this cookie (unless it has expired) with a http request header like this:
Cookie: name=value
The session mechanisms in the backend (being PHP in your case) linked the unique id of the cookie with data that has been stored in a file in the servers filesystem, or perhaps in a database. This way, each time the cookie is received it is able to retrieve this data and link it to the request.
The advantage of this, is that sensitive information 1) can be hidden from not having to travel over the net, and 2) doesn't end up in the users browser cookie cache, by keeping it at the server.
So, basically you want to send non-sensitive, and non-application-vital information in a regular cookie (think of: layout preferences, a non-persistant playlist such as on YouTube perhaps, etc.), and use a session to store sensitive information.
edit:
Sorry, ignore the "or the expiration date is set to a date in the past", as it was false. This will cause the cookie to immediately be invalidated by the browser, and thus not be sent along with requests anymore.
The advantage of using cookies over sessions is that cookies are persistent.
In other words, when the user visits your site weeks later, their session has more than likely expired. However, if they have a cookie that can uniquely identify them to your script, then you can automatically log them in and reestablish the session.
...what circumstances would each be appropriate for?
The answer looks something like this:
Session data should contain information that does not need to be persistent or is only needed for a short period of time. For example, if you are presenting a multiple-page form to the user, it makes sense to take advantage of sessions.
Cookies should be used to store an ID or hash that uniquely identifies not only the user, but also the browser / device they are logged in with. Keep in mind that cookie data is out of your control and can only be manipulated / removed by HTTP requests made by the user (or under certain circumstances, by a script on a page).
Also, i have seen people say that the cookie could be used to store a session id...
I'm assuming what was meant by that is storing a unique value in a cookie that identifies the user / browser / device that they are using. Implementing something like this would look like:
Let the user log in as they would normally.
Generate a unique hash (SHA-1 is your best bet) and store that in a cookie. You also store the hash in a database linked to that user.
...
The user returns after their session has expired and visits a page.
Your script sees the cookie and looks up the user that the hash belongs to.
The user is logged in.
Both cookies and sessions are used to keep user-specific information in order to track a user. A lot of times you can use either one, but they have some differences.
A cookie is a text file kept on the user's machine. Every time the users visits your site he hands over the cookie letting you know who he is. The advantage of this is that the information is kept on somebody else's machine so you don't have to worry about it. As such you can leave it there until the cows come home. When/if the user comes back he'll bring the information with him. The downside is that the information is out of your control because the user can easily edit the cookie you gave him. This makes any information in a cookie untrustworthy and has to be checked every time the user gives it to you.
A session is like a cookie except you keep the information on your server. The advantage is that you can trust a session to keep data exactly like it was when you put it in. The downside is that you have to store that information which means that eventually you'll need to discard it lest your webserver fills up with information that will never be used.
Now this is where it gets a bit tricky. You see while the mechanism of a session is as I described above, the actual implementation can vary depending on PHP's settings. The session data can be kept in individual text files or in a database on your server. Also you need some way of recognizing which session corresponds to which user. The usual (but not only) way to do this is with cookies. What happens is that the actual data stays on your server and is linked to a unique session id. That session id number is put on a cookie and given to the user so you can later look up his data when he comes back.
The above process is performed automatically by PHP when you use the session functions; you do not need to implement it by hand. If for whatever reason you need to change how sessions are implemented you can do so by changing the session parameters in php.ini.

Categories