Cookie для www php

PHP Cookies

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

Create Cookies With PHP

A cookie is created with the setcookie() function.

Syntax

Only the name parameter is required. All other parameters are optional.

The following example creates a cookie named «user» with the value «John Doe». The cookie will expire after 30 days (86400 * 30). The «/» means that the cookie is available in entire website (otherwise, select the directory you prefer).

We then retrieve the value of the cookie «user» (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:

Example

$cookie_name = «user»;
$cookie_value = «John Doe»;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), «/»); // 86400 = 1 day
?>

if(!isset($_COOKIE[$cookie_name])) echo «Cookie named ‘» . $cookie_name . «‘ is not set!»;
> else echo «Cookie ‘» . $cookie_name . «‘ is set!
«;
echo «Value is: » . $_COOKIE[$cookie_name];
>
?>

Note: The setcookie() function must appear BEFORE the tag.

Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

To modify a cookie, just set (again) the cookie using the setcookie() function:

Example

$cookie_name = «user»;
$cookie_value = «Alex Porter»;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), «/»);
?>

if(!isset($_COOKIE[$cookie_name])) echo «Cookie named ‘» . $cookie_name . «‘ is not set!»;
> else echo «Cookie ‘» . $cookie_name . «‘ is set!
«;
echo «Value is: » . $_COOKIE[$cookie_name];
>
?>

To delete a cookie, use the setcookie() function with an expiration date in the past:

Example

echo «Cookie ‘user’ is deleted.»;
?>

Check if Cookies are Enabled

The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:

Example

if(count($_COOKIE) > 0) echo «Cookies are enabled.»;
> else echo «Cookies are disabled.»;
>
?>

Complete PHP Network Reference

For a complete reference of Network functions, go to our complete PHP Network Reference.

Источник

PHP Cookies

Summary: in this tutorial, you’ll learn about cookies and how to use the PHP setcookie() function to manage cookies effectively.

Introduction to cookies

The web works based on the HTTP protocol. The HTTP protocol is stateless.

When the web browser requests a page from a web server, the webserver responds with the page content. Later, the same web browser requests the same page again, and the webserver has no information that the request is from the same web browser.

Читайте также:  Parsing xml in python example

Cookies solve this stateless challenge.

A cookie is a piece of data that a web server sends to the web browser. The web browser may store it and send it back in the subsequent requests to the same web server. The web server knows that two requests come from the same web browser by using the same cookie.

Cookies are also known as web cookies, HTTP cookies, or browser cookies. We’ll use the cookies to make it short.

The following flow chart illustrates how cookies work:

PHP cookie

  • First, the web browser sends a request to the web server. The web server doesn’t have any information about the web browser. The web server creates a cookie with a name return and a value 1 and attaches the cookie to the HTTP response header. To create a cookie, you’ll use the setcookie() function.
  • Second, the web browser stores the cookie.
  • Third, the web browser sends the second request with the stored cookie in the header of the HTTP request to the web server. On the web server, PHP can access the cookie via the $_COOKIE superglobal variable and do something accordingly.
  • Finally, the web server responds with the content of the request. Typically, it responds to the web browser with the content based on the value of the cookie.

A web browser can store a cookie with a maximum size of 4KB. However, it’s different between web browsers.

A cookie has an expiration date. Typically, web browsers store cookies for a specific duration. And the web server can specify the expired time for a cookie.

A cookie also stores the web address (URL) that indicates the URL which created the cookie. And the web browser can send back the cookie that was originally set by the same web address. In other words, a website won’t be able to read a cookie set by other websites.

Most modern web browsers allow users to choose to accept cookies. Therefore, you should not wholly rely on cookies for storing critical data.

Why using cookies

In general, websites use cookies to enhance user experiences. For example, you would have to log in to a website again after you leave it without cookies.

Typically, you’ll use cookies for the following purposes:

  • Session management: cookies allow a website to remember users and their login information or anything else that the web server should remember.
  • Personalization: cookies can store user’s preferences, themes, and other settings.
  • Tracking: cookies store user behavior. For example, on an Ecomerce website, you can use cookies to record the products that users previously viewed. Later, you can use this information to recommend the related products that users might be interested in.

PHP makes it easy to work with cookies using the setcookie() function. The setcookie() function allows you to send an HTTP header to create a cookie on the web browser.

 setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false ): boolCode language: HTML, XML (xml)

The following table illustrates the arguments of the setcookie() function:

Argument Meaning
$name The name of the cookie
$value The value of the cookie. It can be any scalar value such as string or integer.
$expires The time (in a UNIX timestamp) the cookie expires. If $expires is not set or set to 0, the cookie will expire when the web browser closes.
$path The path on the webserver on which the cookie will be available. For example, if the path is ‘/’, the cookie will be available within the domain.
$domain The domain to which the cookie will be available.
$secure if $secure is set to true , the cookie should be transmitted over a secured HTTP (HTTPS) connection from the web browser.
$httponly if $httponly is true, the cookie can be accessed only via the HTTP protocol, not JavaScript.

As of PHP 7.3.0, you can use the same setcookie() function with an alternative signature:

setcookie ( string $name , string $value = "" , array $options = [] ) : boolCode language: PHP (php)

The $options argument is an array that has one or more keys, such as expires , path , domain , secure , httponly and samesite . The samesite can take a value of None , Lax , or Strict . If you use any other key, the setcookie() function will raise a warning.

The setcookie() function returns true if it successfully executes. Notice that it doesn’t indicate whether the web browser accepts the cookie or not. The setcookie() function returns false if it fails.

The $_COOKIE an associative array that stores the HTTP cookies. To access a cookie by a name, you use the following syntax:

$_COOKIE['cookie_name']Code language: PHP (php)

If the cookie name contains dots ( . ) and spaces ( ‘ ‘ ), you need to replace them with underscores ( _ ).

To check if a cookie is set, you use the isset() function:

 if(isset($_COOKIE['cookie_name'])) Code language: HTML, XML (xml)

The $_COOKIE is a superglobal variable, so it can be accessed from anywhere in the script.

Before reading a cookie value, you should always check if it has been set by using the isset() function:

 if (isset($_COOKIE['cookie_name'])) < // process the cookie value >Code language: HTML, XML (xml)

To check if a cookie equals a value, you use the following code:

 if (isset($_COOKIE['cookie_name']) && $_COOKIE['cookie_name'] == 'value') < // . >Code language: HTML, XML (xml)

If you don’t use a cookie, you can force the browser to delete it. PHP doesn’t provide a function that directly deletes a cookie. However, you can delete a cookie using the setcookie() function by setting the expiration date to the past.

The following code deletes a cookie with the cookie_name in the subsequent page request:

unset($_COOKIE['cookie_name']); setcookie('cookie_name', null, time()-3600); Code language: PHP (php)

The following example shows how to use a cookie to display a greeting message to a new or returning visitor.

 define('ONE_WEEK', 7 * 86400); $returning_visitor = false; if (!isset($_COOKIE['return'])) < setcookie('return', '1', time() + ONE_WEEK); > else < $returning_visitor = true; > echo $returning_visitor ? 'Welcome back!' : 'Welcome to my website!'; Code language: HTML, XML (xml)

First, define a constant that stores one week in second:

define('ONE_WEEK', 7 * 86400); Code language: JavaScript (javascript)

Second, set the returning_visitor to false:

$returning_visitor = false;Code language: PHP (php)

Third, check the cookie with the name return. If the cookie is not set, create it with the value one and the expiration date one week. Otherwise, set the $returning_visitor variable to true.

if (!isset($_COOKIE['return'])) < setcookie('return', '1', time() + ONE_WEEK); > else < $returning_visitor = true; >Code language: PHP (php)

Finally, display the greeting message based on the value of the $returning_visitor variable.

When you request the page for the first time, you’ll see the following message:

And if you open the web developer tool, you’ll see the cookie as shown in the following picture:

Since the web browser already stores the cookie with the name return and value 1 , if you refresh the page, you’ll see a different message:

This cookie will last for seven days set by the webserver. Of course, from the web browser, you can manually delete the cookie.

Summary

  • A cookie is a piece of data that the web server sends to a web browser to check if two requests come from the same web browser.
  • Use the PHP setcookie() function to set a cookie that is sent along with HTTP header from the web server to the web browser.
  • Use the superglobal variable $_COOKIE to access the cookies in PHP.

Источник

Cookies

PHP прозрачно поддерживает HTTP cookies. Cookies — это механизм хранения данных браузером удалённой машины для отслеживания или идентификации возвращающихся посетителей. Вы можете установить cookies при помощи функций setcookie() или setrawcookie() . Cookies являются частью HTTP -заголовка, поэтому setcookie() должна вызываться до любого вывода данных в браузер. Это то же самое ограничение, которое имеет функция header() . Вы можете использовать функции буферизации вывода, чтобы задержать вывод результатов работы скрипта до того момента, когда будет известно, понадобится ли установка cookies или других заголовков.

Любые cookies, отправленные серверу браузером клиента, будут автоматически включены в суперглобальный массив $_COOKIE , если директива variables_order содержит букву «C». Для назначения нескольких значений одной cookie, просто добавьте [] к её имени.

Дополнительная информация, в том числе и особенности реализации браузеров, приведена в описании функций setcookie() и setrawcookie() .

User Contributed Notes 1 note

// Example
// Setting a cookie
setcookie ( «usertoken» , «noice» , time ()+ 20 * 24 * 60 * 60 );
// 20 days = 20*24*60*60 seconds

setcookie ( «usertoken» , «» , time ()- 3600 )
?>

  • Отличительные особенности
    • HTTP-​аутентификация в PHP
    • Cookies
    • Сессии
    • Работа с XForms
    • Загрузка файлов на сервер
    • Работа с удалёнными файлами
    • Работа с соединениями
    • Постоянные соединения с базами данных
    • Использование PHP в командной строке
    • Сборка мусора
    • Динамическая трассировка DTrace

    Источник

Оцените статью