Cookies in PHP
How to use cookies in PHP
Cookies in PHP is done by using the statement setcookie() , this statement is available from the time when version 3 of PHP.
int setcookie (string Name [, string Value [, int Expire [, string Path [, string Domain [, int Secure]]]]]);
setcookie() defines a cookie that is sent the information from the header. Cookies are sent before any html tag; therefore, we call one of these statements before any tag <html> or <head>. This is a restriction of cookies, not for PHP.
All messages, except the name are optional.
- Name . Name of the cookie. If we create a cookie only with its name, the cookie name is existing in the Client under said name will be deleted. We can also replace to any argument with an empty string(“”).
- Value . Value to be stored by the cookie in the Client.
- Expire . The argument expire is an integer argument that indicates the time of the cookie will be deleted in the time format returned by the UNIX statements time() and mktime(). Time() + N seconds of duration is commonly used to specify the duration of the cookie.
- Path . Subdirectory where the cookie has a value.
- Domain . Domain where the cookie has a value. If we establish www.yourdomain.com as domain, the cookie is not set for domain.com. Meanwhile, if we establish yourdomain.com as domain, the cookie is set as for yourdomain.com as for www. yourdomain.com.
- Secure . The secure indicates that the cookie will only be set by a secure HTTPS connection.
Example
setcookie(“Ron”, “Victor”, time()+3600,”/”,”yahoo.com”);
In this example, we set a user name cookie that has the value Victor , lasts 1 hour (3600 seconds) valid for the whole domain yahoo.com