- Declaring the cookie: As always it is best to check out the PHP.net reference guidefor the full details about a built-in function.
//Sets a cookie name "cookie", expires on browser close setcookie("Cookie", $data); //Sets a cookie name "cookie", expires in an hour setcookie("Cookie", $data, time()+3600); //Sets a cookie name "cookie", expire in an hour, only valid in admin directory, accessible only via HTTP setcookie("Cookie", $data, time()+3600, "/admin/", ".domain.com", 1);
- Prevent XSS Attacks: Cross-Site-Scripting (XSS) attacks are a major security issue. Any user inputted data into your site should be cleared of HTML entities to prevent JavaScript insertion. In the last example, the last parameter is set to "1" which enables httponly helping prevent JavaScript from accessing the cookie.
- Proper Placement: Since setcookie() is adding a header to the web page, setcookie() must be displayed before any other output is sent to the browser. This is something major to remember. That means a simple PHP error message thrown before the setcookie() is called could prevent the cookie from being set.
Want more? Sign up for my weekly newsletter