Cookies

Содержание
What cookies are
Example
Creating cookies
Cookie options
Example of setting options
Demo in your browser
Deleting cookies
Drawbacks

What cookies are

Cookies are files up to 4KB exchanged over HTTP or HTTPS between an HTTP client (browser) and an HTTP server.

A user visits a site through a browser. The browser makes a GET request. The server returns a response containing cookie data.

The browser creates a cookie file with this data. Then the user may go to another page of the site - a new GET request, but it already carries the cookie contents.

The server appends something and so they keep passing cookies back and forth.

Example

Example client request

Request 1 GET /homepage.php HTTP/1.1 Host: eth1.ru Accept: */*

Server response

Response 1 HTTP/1.1 200 OK Content-type: text/html Set-Cookie: lang=rus

A request to another page already carries cookies

Request 2 GET /aboutus.php HTTP/1.1 Host: eth1.ru Cookie: lang=rus Accept: */*

Roughly speaking, this is how cookies remember user settings

Creating cookies with PHP

<?php setcookie(string $name, string $value="", array $options=[]) : bool

Let us go through the parameters

name

The cookie name - helps extract values from the $_COOKIE superglobal variable

value

Data recorded in cookies

options

It is an associative array (can be called a dictionary for short) with a set of keys:

Using another key leads to E_WARNING

Let us examine these six options in detail

Cookie options

expires: specifies when cookies expire.

Used together with the time() function, which sets the starting moment.



Example:

Without expires, cookies are deleted every time the page is reopened.

path: server path or domain path the cookie is sent to



Example:

Suppose the domain is eth1.ru. Setting the path to '/php/'

setcookie(name, value, time()+3600, '/php/');

Then cookies are sent only with requests to eth1.ru/php and subdirectories

Setting path to / sends cookies regardless of which file is requested.

setcookie(name, value, time()+3600, '/');

eth1.ru/*

domain: Sets the domain cookies are sent to.



Example:

Setting www.eth1.ru works only with www.urn.su

Setting eth1.ru also works with all subdomains

secure: setting TRUE sends cookies over HTTPS only. Default is FALSE

httponly: cookies are available over HTTP (and HTTPS) only. That is, JavaScript or bbscripts cannot access cookies

samesite: sets cookie sending rules for cross-site requests.


Three variants possible:

Example of using $options

$options = array ( 'expires' => time() + 60*60*24, 'path' => ' /' , 'domain' => '.eth1.ru' , 'secure' => true, // or false 'httponly' => true, // or false 'samesite' => 'None' // or Lax or Strict ); setcookie('lang', 'rus', $options);

Using cookies

To see cookies working right in your browser - go to next article:

«Cookies demo»

Following the link you allow this site to create cookies. They are off by default, but that page cannot work without them.

On the page 1_form.php you can enter any number in the form. It is recorded in cookies your_number

On the page 1_result.php you can see that cookies your_number are really created

On the page 2_form.php cookies are checked for presence name .

If cookies name were already set, you see a personalized greeting.

If not set, you are asked to fill the form again.

And then on the page 2_result.php you see a personalized message

Delete cookies

Deleting cookies with unset() does not work because they stay on the client. The browser simply sends them as if nothing happened.

To delete cookies do it on the server + send the browser a delete command.

This command sets a zero or negative time in expires

options['expires'] = time() - x setcookie(name, value, options);

Example

$options['expires'] = time() - 3600; setcookie(name, $_COOKIE['name'], $options); unset($_COOKIE['name']);

Limitations

To work around these limitations use sessions

Article author: Andrei Olegovich

Похожие статьи
Development with PHP
Arrays in PHP
Date and Time in PHP - basics
How to display time of multiple timezones in PHP
How to add variable to url in PHP
json_decode
How to get screen size with PHP
Call function from another file
Premature end of chunk coded message body: closing chunk expected
Generate unique random numbers with PHP
Check your HTTP_USER_AGENT
Compare two dates
OOP
Namespaces in PHP
Comments in PHP
Cookies
PHP sessions
Authentication and Authorization in PHP 8
PHP linters we use
PHP errors: case studies
card_from_db(): banner card from a DB row
PHP versions: history in brief
Creating rules in .htaccess
require, require_once, include, include_once
Flat pair arrays: three pitfalls from the Related articles block
Deduplication in PHP
PHP course: zero to hero in 50 lessons

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: