Skip to main content

Setting Cookies with PHP

Published on
If you plan on building a PHP application, you'll probably end up using cookies, especially if there are user accounts. Cookies will allow you to store specific data for a certain amount of time. Here are some tips and tricks to make sure you do not run into too many problems.
  1. 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);
  2. 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.
  3. 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.

I'm available for one-on-one consulting calls – click here to book a meeting with me 🗓️