PHP - Setting a Cookie in PHP

Introduction

PHP setcookie() function can send the appropriate HTTP header to create the cookie on the browser.

This accepts arguments for each of the cookie fields.

Only the name argument is required, it's a good idea to supply at least name, value, expires, and path to avoid any ambiguity.

The expires argument should be in UNIX timestamp format.

Call setcookie() before sending any output to the browser.

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


setcookie("Size" , 3, time() + 60 * 60 * 24 * 365," /" ," .example.com" , false, true);

The expires argument uses a PHP function called time(). This returns the current time in UNIX timestamp format.

You can update an existing cookie simply by calling setcookie() with the cookie name and the new value.

You need to supply the path and expires arguments when updating the cookie:

setcookie(" pageViews" , 8, 0," /" ," " , false, true);

Related Topic