Tag Archives: Home

Setting Cookies from PHP

You can manually set cookies in PHP using the setcookie() function. It has the
following prototype:
bool setcookie (string name [, string value [, int expire [, string path
[, string domain [, int secure]]]]])
The parameters correspond exactly to the ones in the Set-Cookie header mentioned
previously.
If you set a cookie as
setcookie (‘mycookie’, ‘value’);

when the user visits the next page in your site (or reloads the current page), you will
have access to the cookie via $_COOKIE[‘mycookie’].
You can delete a cookie by calling setcookie() again with the same cookie name
and an expiry time in the past.You can also set a cookie manually via the header()
function and the cookie syntax given previously. One tip is that cookie headers must be sent before any other headers; otherwise, they will not work. (This is a cookie limitation rather than a PHP limitation.)

Advertisements