Originally posted by alsaffar
[Which one is better to use for user's authentication, cookies or sessions?
I have been seriously investigating such questions and still find myself on the beginning of the learning curve and open to suggestion, but from what I have found out so far that is not really a fair question in itself, which one is 'better'. Sessions and cookies are not a one verses the other. Sessions do two jobs, maintaining state and offering a convenient and relatively secure place to store variables.
Sessions are not just authentication, they are a kind of a built in package to take the load off you as a programmer. Sessions use cookies by default to maintain state but URL encoding the session ID is also available, and kicks in automatically if the user has cookies turned off. If you wish to store a variable in a session it is kept track of by the server and unavailable to packet sniffers.
The price you pay may be a performance hit, possibly a significant one. Sessions have a built in additional overhead per visitor on top of everything else which is the RAM used for storing the various pointers and whatnot per session, the extent of which I have not yet been able to find documented for PHP. With JSP the amount quoted to me was 256k per user, with IIS it was 'probably quite a bit', I have not found anything to indicate how much PHP uses.
Another consideration when sessions are turned on may be whether you really need to maintain state on ALL your visitors. If you have a shopping site with 2000 visitors but only 20 of have evoked the shopping cart, do you really need to maintain state with the other 1,980 visitors? Even if the sessions are not authenticated, the server still might partition RAM to keep track that this user/session is NOT authenticated. This is one question that I have been unable to find the answer to, but with other server languages you are indeed suffering the additional overhead.
On the other side of the coin, everything a session does is available to you also, but you then need to handle everything with your scripts. To maintain state, you can generate a unique ID and place it in a cookie or encode it in the URL just as a session does. Storing the variables then becomes your responsibility also. You can either store them in files as sessions do, put them in a database, or put them in the cookie (which may have some serious performance and security considerations).
So far from what I have been able to dig up there is not really one answer. Depending on your site you may be able to handle state and store variables much more efficiently on your own, or you just might find that sessions pay for themselves.