Setting a Cookie in PHP

Setting a Cookie in PHP PHP provides a built – in function, setcookie() , that can send the appropriate HTTP header to create the cookie on the browser.

Here, you will learn how to set a cookie. You should always call setcookie() before sending any output to the browser. This is because setcookie() needs to send the Set – Cookie: HTTP header.

Here is an example that uses setcookie() to create a cookie storing the user’s font size preference ( 3 in this case):

setcookie( “fontSize”, 3, time() + 60 * 60 * 24 * 365, “/”, “.example.com”, false, true );

Notice that the expires argument uses a PHP function called time() . This returns the current time in UNIX timestamp format. So the expiry time is 60 * 60 * 24 * 365 seconds after the current time, or one year into the future. The cookie will remain until that time, even if the browser is closed and reopened, unless the user chooses to delete it manually.