Search code examples
phpcookiessetcookie

Create unique dynamic cookie until delete cookie


How to create unique dynamic cookie until the cookie is deleted. I am using

 setcookie("name",uniqid(), 0, "/");

But its generates a new name for every page load but I want only one name until the cookie is deleted.


Solution

  • You need to first check if the user has a cookie set, and if it contains the information you're looking to save in it. If it isn't set, then you create a new name for it. If it's set, re-create it using the same name.
    To test whether or not it's set, then you need to loop through the $_COOOKIES array, and check for a specific key. Which is a rather haevy-handed approach.

    That is why this is, generally, not the best of ideas. As the name of the cookie should be static, but rather contain a randomly created key that points to the content in a DB. Makes checking for the cookie easy, and it helps you save the data out of the reach from the user (to prevent manipulation).

    That said this sounds very much like a session, unless you want the cookie to persist even if the browser is closed. If this is not a concern, and the cookie should be deleted when the browser is closed, I recommend just using the sessions instead: Much simpler. :)