Analysis of PHP Cookies and Sessions (Repost)

by stilling2006 on 2008-12-01 12:27:47

A cookie is a mechanism for storing data on the remote browser side and using it to track and identify users. PHP sends cookies in the HTTP header, so the `setcookie()` function must be called before any other information is output to the browser. This restriction is similar to that of the `header()` function.

1.1 Setting Cookies:

Cookies can be set using the `setcookie()` or `setrawcookie()` functions. They can also be set by directly sending an HTTP header to the client.

1.1.1 Using the `setcookie()` function to set a cookie:

```php

bool setcookie ( string $name [, string $value [, int $expire [, string $path [, string $domain [, bool $secure [, bool $httponly]]]]]] )

```

- `$name`: The name of the cookie variable.

- `$value`: The value of the cookie variable.

- `$expire`: The timestamp when the cookie will expire.

- `$path`: The directory where the cookie is valid.

- `$domain`: The domain where the cookie is valid; top-level domain only.

- `$secure`: If set to 1, the cookie will only be transmitted over HTTPS. If set to 0 (default), it will work over both HTTP and HTTPS.

Example: