How do you use cookies in PHP?

How do you use cookies in PHP?

You can set a cookie using the "setcookie()" function, which takes the following arguments:


setcookie($name, $value, $lifetime, $path, $domain, $secure, $httponly);


$name = The name of the cookie (String)


$value = (Optional) The value of the cookie, like a username or code (String)


$lifetime = (Optional) The lifetime of the cookie (Integer of seconds)


$path = (Optional) The directory / path of a server, in which the cookie will be available in (String)


$domain = (Optional) The domain name at which the cookie is available at (String)


$secure = (Optional) Determines whether the cookie should only be sent while there is a secure connection (If you don't know what this is, just make it false) (Boolean)


$httponly = (Optional) Determines whether the cookie can only be accessed through the HTTP protocol, and not by other scripting languages like JavaScript or VBScript (Boolean)


The only arguments you need to focus on here, for starters, is the $name, $value, and $lifetime. All other arguments are optional and can be left alone, just for the purpose of learning how to set a cookie.


Here is an example of how you could set up a cookie:


Setting a cookie



setcookie('mycookie', 'hello', time()+3600);


We set the name of the cookie to "mycookie".


We said the value of the cookie is "hello".


We said that the cookie should expire at the current time + 3,600 seconds. This means that the cookie should delete itself after 3,600 seconds.


Displaying a cookie's value


Now that you have set the cookie, your going to need to retrieve it. When you send a cookie, it won't be available on the same page - you must go to another page, or refresh the page, to have the cookie truly "set".


The $_COOKIE variable contains all the values of every cookie, stored on a user's computer, that is available to the website.


You can access a specific cookie by putting it's name into the $_COOKIE array. For example, in our case, we would say $_COOKIE['mycookie'] to retrieve our cookie information.


echo $_COOKIE['mycookie']; // Displays "hello"


Changing the value of a cookie


You can also alter the value of a cookie by "setting" the cookie again, but with a different value.


setcookie('mycookie', 'its a different value!', time()+3600);


Deleting a cookie


And, of course, you may want to delete cookies. There isn't a specific delete-cookie function. However, you can "set" the cookie again, and specify a time in the past - so then the browser should immediately dispense of the cookie.


You won't need a value, since it's going to delete itself anyway. You can go ahead and set it to the NULL constant (or, give it a value - either way works).


setcookie('mycookie', NULL, time()-3600);


// or


setcookie('mycookie', 'goodbye', time()-3600);


// or




For more information about cookies, see the PHP and w3schools references, respectively listed.


[ ]


[ ]