Search code examples
phpcookiessetcookie

Check Coockies created by the server not by the user


I was creating a login system but I ran into an issue. I have to use PHP COOKIES. A cookie is created when a user enters the correct username and password. "user=22" or "user=23" etc. But a user can go to the console panel and create this cookie themselves with document.cookie.

isset($_COOKIE["user"]) returns true even if the cookie is created by user in console panel. So, I have to check the cookies created by the server. Is there a way to do it? Let me know if there is a better way to fix this problem :)


Solution

  • A really important thing to understand about web programming is that everything in the request is in the user's control. The browser, or whatever software the user chooses, can send your server whatever request they want. All you can do is read that request, and decide what to do.

    In this case, the browser is sending a cookie claiming they are a logged-in user; you have to decide whether to trust that claim.

    You could make use of a cryptographic signature: when you set the cookie, include a signature using a private key that never leaves the server; then when a browser presents a cookie, verify the signature to see whether they are sending you back a value which you sent.

    More simply, and more flexibly, you can make the cookie an opaque random value, and store information on the server associated with that value. This is the idea behind PHP's session functionality: a random identifier is generated, and sent to the browser in a cookie. When the browser sends back that random identifier, you can look up the information associated.

    Sessions have a number of advantages, such as being able to store a larger amount of data; and reliably update or invalidate that data (you can ask the user's browser to delete a cookie, but you can't guarantee that it will do so, because the user is in control). Their main disadvantage is the requirement to store central state somewhere, which is tricky when "scaling out" to multiple web servers.