PHP make easier by providing setcookie function to allow you to set cookie. Once cookie is set, you can access it through the super global array $_COOKIE.
Here is form of setcookie function.
setcookie($name, $value, $expire, $path, $domain, $secure);
- $name: Cookie’s name. As always it should be meaningful.
- $value: Value of the cookie. It can be scalar value such as string or integer
- $expire: Time to expire in UNIX timestamp. If time to expire is not set cookie will expire when user close the web browser.; for example: time()+”7200″. Cookie will be expired in two hours.
- $path: The path on your web server for which the cookie will be returned.
- $domain: domain where cookie will be returned.
- $secure: true to indicate cookie is set over secured HTTP (HTTPS). Default value is false
Here the sample of setting cookie :
<?php
setcookie(“user”,”newbiekid”,time() + 3600);
?>
<html>
<body>
<p>Cookie has been set to user newbiekid and will be expired in 1 hours.</p>
</body>
</html>
Be noted that cookie must be set before any HTML code as shown above.This is because cookies are headers and must come before the body of the request.
Once cookie has been set you can get its value via superglobal array $_COOKIE. Before reading cookie value you should check whether the cookie is available by using isset function. Here is the code sample to read cookie value:
