PHP Cookies

PHP Tutorial

 PHP Cookies Tutorial

PHP Cookies are small pieces of data stored on the user’s browser. It can create, read, and delete cookies to track user activity, preferences, or login information.


 Setting a Cookie


 

Parameters of setcookie()

ParameterDescription
nameName of the cookie
valueValue stored in the cookie
expireExpiration time in seconds (time() + seconds)
pathPath on the server where cookie is available (/ = entire website)
domainDomain that can access the cookie
securetrue if HTTPS only
httponlytrue to prevent JavaScript access (more secure)

Must call setcookie() before any HTML output.


 Accessing a Cookie


 

  • Use $_COOKIE['name'] to access the cookie value.

  • Cookies are stored on the client-side, sent with each request.


 Modifying a Cookie

To change a cookie, set it again with the same name and new value:


 


 Deleting a Cookie

To delete a cookie, set its expiration time in the past:


 


 Example: Complete Cookie Example


 


 Key Points

  1. Cookies are store on the client browser.

  2. Expire automatically after specified time.

  3. Use $_COOKIE to read cookie values.

  4. setcookie() must be call before any HTML output.

  5. Can store user preferences, login info, or tracking data.

You may also like...