Cookies in PHP

In PHP, cookies can be used to store small amounts of data on the user's computer. They are often used to remember information about the user, such as their login credentials or preferences.

To create a cookie in PHP, you use the setcookie() function. This function takes several parameters, including the name of the cookie, the value to be stored, and optional parameters such as expiration time and path.

Here is an example of creating a cookie in PHP:

```
<?php
// Set a cookie with the name "username" and value "john"
setcookie("username", "john");

// Set a cookie with the name "theme" and value "dark" that expires in 1 hour
setcookie("theme", "dark", time() + 3600);

// Set a cookie with the name "location" and value "New York" that is only accessible within the "/example" directory
setcookie("location", "New York", time() + 3600, "/example");
?>
```

To access the value of a cookie, you can use the $_COOKIE superglobal variable. This variable is an associative array where the keys are the names of the cookies and the values are the corresponding values.

Here is an example of accessing a cookie value in PHP:

```
<?php
// Check if a cookie named "username" exists
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"];
}
?>
```

To delete a cookie, you can set its expiration time to a past value, causing it to expire immediately. Here is an example:

```
<?php
// Delete a cookie named "username" by setting its expiration time to a past value
setcookie("username", "", time() - 3600);
?>
```

Note that cookies are sent from the user's browser to the server with every request, so they should not be used to store sensitive information such as passwords.