Create, Remove or Read a PHP Cookie using Setcookie method

HTTP is a stateless protocol. During Client Server communication to maintain state we use some techniques. Cookie is one of them. Generally we use Cookies to identify an user. When first time user send request to the server in response server sends a set of Cookies. Which browser stores in Client machine. Next time when the same user request again browser send the information store in Cookies. Through which server get to identify the user.

Cookie is a text file. It can store maximum upto 4mb data. While creating a Cookie its mandatory to provide Expiry date. Compare to session Cookies is not secured. For programmers it is advisable to not store secured data in Cookies. PHP is a server side programming language. In this session let us share Cookie related operations using PHP.

What are Cookies?

Cookies are small pieces of data stored on a user’s device by a web browser while browsing a website. They are used to remember user preferences, track sessions, and enhance user experience. In PHP, cookies are a fundamental tool for maintaining state between page loads, as HTTP is a stateless protocol.

In PHP to create a Cookie there is a setcookie() method. setcookie accepts 6 parameters. The syntax to create Cookie in PHP is as below.

setcookie(name, value, expire, path, domain, security);

PHP setcookie() method parameters

name Using this parameter you can set the name of the Cookie. In future if you want to access value of the Cookie name is required. Physically Cookie name stored in an environment variable HTTP_COOKIE_VARS.
value Cookie stores data in key value pair. Key is the name where value is the real data.
expire While creating a Cookies we need to decide how long the cookie need to reside in Client machine. This can be set using expire property. By default if you will not set expire time cookie will get destroy after browser get close.
path Path specifies the physical directories for which the cookie is valid. Using single forward slash permits the cookie to be valid for all directories.
domain Using this property you can specify the domain name in very large domains. By default all cookies are only valid for the host & domain which created them.
security This parameter accepts 2 values 1 or 0. By passing 1 you can specify that cookie need to travel only by secure transmission (HTTPS). By passing 0 cookie can be travel using regular HTTP.

PHP Write Cookie Example using Setcookie

<?php
setcookie("empName", "Baby Roy", time()+3600, "/","", 0);
setcookie("empID", "996782", time()+3600, "/", "",  0);
?>

Read a PHP Cookie?

There are 2 methods to access Cookies in PHP. $_COOKIE & $HTTP_COOKIE_VARS.

<?php
echo $HTTP_COOKIE_VARS["empName"];
echo $_COOKIE["empID"];
?>

PHP Check Cookie Example

In PHP there is a method isset() using this you can know whether there is a Cookie exists or not. Look at the example below.

<?php
if( isset($_COOKIE["empName"]))
echo "Welcome " . $_COOKIE["empName"];
else
echo "No Cookies";
?>

PHP Remove Cookies Example

To delete a Cookie in PHP you required to set expiry time less than the current time. For an example refer to above we have two cookies empName & empID. To delete these cookies we required to call setcookie() method with expiry time less than the Current time. Look at the example below.

<?php
setcookie("empName", "Baby Roy", time()-60, "/","", 0);
setcookie("empID", "996782", time()-60, "/", "",  0);
?>

Common Use Cases for PHP Cookies

1. Session Management Cookies are often used to maintain user sessions. For example, an e-commerce site might use cookies to keep track of a user’s shopping cart.

2. Personalization Websites use cookies to remember user preferences, such as language settings or theme choices.

3. Tracking and Analytics Cookies help websites gather data on user behavior, enabling improvements in content and marketing strategies.

Security Considerations

1. Cross-Site Scripting (XSS) If a cookie is not set with `HttpOnly`, JavaScript can access it, making it vulnerable to XSS attacks.

2. Cross-Site Request Forgery (CSRF) Attackers can manipulate cookies to perform unauthorized actions. Using secure tokens helps mitigate this risk.

3. Data Privacy Compliance Regulations like GDPR require websites to obtain user consent before storing non-essential cookies.

Best Practices for Using PHP Cookies

1. Use ‘HttpOnly’ and ‘Secure’ Flags: Prevent JavaScript access and ensure cookies are transmitted securely.
2. Limit Cookie Lifespan: Avoid setting excessively long expiration times.
3. Encrypt Sensitive Data: Never store passwords or personal information directly in cookies.
4. Validate and Sanitize Input: Prevent malicious data from being stored in cookies.

Alternatives to PHP Cookies

1. Sessions PHP sessions store data on the server, making them more secure than cookies. However, they still rely on a session ID stored in a cookie.

2. LocalStorage and SessionStorage JavaScript-based storage options that persist data on the client side but are not sent to the server with every request.

Conclusion

PHP cookies are essential for maintaining user state and improving website functionality. By understanding their usage, security implications, and best practices, developers can implement cookies effectively while safeguarding user data. Whether for session management, personalization, or analytics, cookies remain a vital tool in web development when used responsibly.