Php cookies expire date

Cookies – это механизм хранения данных браузером для отслеживания или идентификации возвращающихся посетителей. В PHP работа с Cookie происходит следующем образом:

Установка cookies

Установка cookies производится функцией setcookie или setrawcookie (без URL-кодирования значения).

Cookie передаются клиенту вместе с другими HTTP-заголовками, поэтому setcookie() должна быть вызвана до вывода в браузер.

setcookie($name, $value, $expires, $path, $domain, $secure, $httponly);

$expires – время жизни (метка времени Unix), если 0 или пропустить аргумент, cookie будут действовать до закрытия браузера.

$path – путь к директории, из которой будут доступны cookie. Если задать ‘/’, cookie будут доступны во всем домене.

$domain – домен, которому доступны cookie. Например, ‘ www.example.com ‘ сделает cookie доступными только в нём. Для того, чтобы сделать cookie доступными для всего домена и поддоменов, нужно указать имя домена ‘ example.com ‘.

$secure – при true значения cookie будут доступны только по HTTPS.

$httponly – при true , cookie будут доступны только через HTTP-протокол.

Пример установки cookies:

// До закрытия браузера setcookie('test-1', 'Значение 1'); // На 1 месяц setcookie('test-1', 'Значение 1', strtotime('+30 days'));

Пример установки массива в cookies:

setcookie('test-2[0]', 'Значение 1'); setcookie('test-2[1]', 'Значение 2'); setcookie('test-2[2]', 'Значение 3');

или

$array = array( 'Значение 1', 'Значение 2', 'Значение 3', ); foreach ($array as $i => $row)

Альтернативная вариант доступен с PHP 7.3.0:

setcookie($name, $value, $options);

Где $options массив, который может содержать любой из ключей: expires , path , domain , secure , httponly и samesite .

Читайте также:  Html css table border width

Значение элемента samesite может быть либо None , Lax или Strict .

setcookie('test-1', 'Значение 1', array( 'expires' => time() + 60 * 60 * 24 * 30, 'path' => '/', 'domain' => 'example.com', 'secure' => true, 'httponly' => true, 'samesite' => 'None' ));

Чтение cookies

После передачи клиенту cookie станут доступны через глобальный массив $_COOKIE при следующей загрузке страницы. Значения cookie также есть в массиве $_REQUEST .

Например, вывести одно конкретное значение cookie:

Вывести массив:

Array ( [0] => Значение 1 [1] => Значение 2 [2] => Значение 3 )

Удаление cookies

Чтобы удалить cookies достаточно в setcookie() , в аргументе $expires указать какое-либо прошедшее время. Например 1 час:

setcookie('test-1', '', time() - 3600);
if (isset($_SERVER['HTTP_COOKIE'])) < $cookies = explode(';', $_SERVER['HTTP_COOKIE']); foreach($cookies as $cookie) < $parts = explode('=', $cookie); $name = trim($parts[0]); setcookie($name, '', time() - 3600); >>

Источник

PHP setcookie() Function

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:


$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];
>
?>

Definition and Usage

The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers.

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.

Читайте также:  Html text type bold

The name of the cookie is automatically assigned to a variable of the same name. For example, if a cookie was sent with the name «user», a variable is automatically created called $user, containing the cookie value.

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).

Syntax

Parameter Values

Parameter Description
name Required. Specifies the name of the cookie
value Optional. Specifies the value of the cookie
expire Optional. Specifies when the cookie expires. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0
path Optional. Specifies the server path of the cookie. If set to «/», the cookie will be available within the entire domain. If set to «/php/», the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in
domain Optional. Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to «example.com». Setting it to www.example.com will make the cookie only available in the www subdomain
secure Optional. Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE
httponly Optional. If set to TRUE the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages). This setting can help to reduce identity theft through XSS attacks. Default is FALSE
Читайте также:  Footer tag for html

Technical Details

Return Value: TRUE on success. FALSE on failure
PHP Version: 4+
PHP Changelog: PHP 5.5 — A Max-Age attribute was included in the Set-Cookie header sent to the client
PHP 5.2 — The httponly parameter was added

More Examples

Example

Several expire dates for cookies:

// cookie will expire when the browser close
setcookie(«myCookie», $value);

// cookie will expire in 1 hour
setcookie(«myCookie», $value, time() + 3600);

// cookie will expire in 1 hour, and will only be available
// within the php directory + all sub-directories of php
setcookie(«myCookie», $value, time() + 3600, «/php/»);
?>

Example

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

$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];
>
?>

Example

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

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

Example

Create 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:

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

Источник

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