To set a cookie in PHP, the inbuilt function setcookie() is used. This function defines the PHP cookie. This cookie is then sent as HTTP request header. The syntax of this PHP function is as given below.
setcookie("cookie_name","cookie_value","expiry_time");
The PHP Cookie also some other arguments alos. You can learn them at the official website of PHP.
Each of the above three argurments (parameters) are discussed below.
- cookie_name - This is the name of the cookie to set. This is a mandatory parameter. You will refer the cookie with this name only.
- cookie_value - This is the value of the cookie. It is optional. If this value is not specified, a null value is set. To access this value you need the cookie name.
- expiry_time - This is an optional parameter. If this parameter is not specified, the cookie is valid only for the current browser session. At the end of the browser session, the cookie will be cleared. This value is given in the form Unix timestamp. So you should use the PHP inbuilt function time() to set this value. Also, this value is relative to client machine not the server.
Since the PHP cookie is sent as the HTTP header, It must be set before any output is sent.
Last but not least, PHP Cookies are sent by the server but they are created on the client machine by the browser only not the server.However, we often use the terms like "cookie set by server etc."
1. setcookie("user","john");
2. setcookie("user","john",time()+60*10);
The first PHP cookie example sets the cookie named user. This cookie will be deleted by the browser as soon as the current browsing session ends. That is the browser window is closed.
The first PHP cookie example sets the cookie named user. This cookie will be deleted by the browser as soon as the current browsing session ends. That is the browser window is closed.
The example 2 of setting cookie in PHP set the similar cookie, but this time this cookie will be persistent for 10 mins. Even if the user closes his browser, The browser will not delete the cookie this time, rather it will wait for exactly 10 minutes before clearing the cookie.
P.S. - You can see the usage of unset function in the arrays section.