Php get cookie value

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 .

Значение элемента 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 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.

Источник

An associative array of variables passed to the current script via HTTP Cookies.

Examples

Example #1 $_COOKIE example

Assuming the «name» cookie has been set earlier

The above example will output something similar to:

Notes

Note:

This is a ‘superglobal’, or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

User Contributed Notes 5 notes

To clarify the previously posted note:

Dots (.) and spaces ( ) in cookie names are being replaced with underscores (_).

The values of $_COOKIE in general are not identic with the values in $_SERVER[«HTTP_COOKIE»]!

In phpinfo() $_SERVER[«HTTP_COOKIE»] shows the actual value stored in the cookie by the browser in 7bit.
In $_COOKIE is this value after a 7bit to 8bit conversion.

When all characters in $_SERVER[«HTTP_COOKIE»] are in ASCII = 7bit, $_COOKIE is displayed in phpinfo(). When one single character is not in ASCII, phpinfo() shows no value!

Although in $_COOKIE is still the 8bit conversion of $_SERVER[«HTTP_COOKIE»]!
The reason: the 8bit conversion alone is not enough to say what characters are meant.
For that the used character-set is necessary.

phpinfo() does not know the character-set and better says nothing.

When using $_COOKIE in a php-generated web page the environment has the info of used character-set and so the meant characters can be displayed.

Three illustrating examples
===========================
A HTML-form is used to get the content which shall be stored in a cookie named «test».

Input string in field «test»: door
$_SERVER[«HTTP_COOKIE»]: test=door
$_COOKIE[«test»]
displayed in phpinfo(): door
displayed in any html page: door

Input string in field «test» (ISO-8859-1 used in form): Tür
$_SERVER[«HTTP_COOKIE»]: test=T%FCr
$_COOKIE[«test»]
displayed in phpinfo(): «»
displayed in a ISO-8859-1-html-page: Tür
(displayed in a UTF-8-html-page: T�r)

Input string in field «test» (UTF-8 used in form): Tür
$_SERVER[«HTTP_COOKIE»]: test=T%C3%BCr
$_COOKIE[«test»]
displayed in phpinfo(): «»
displayed in a UTF-8-html-page: Tür
(displayed in a ISO-8859-1-html-page: Tür)

PHP replaces dots (.) with underscores (_). To find all original cookie names (and value) you can use $_SERVER[‘HTTP_COOKIE’].

For example to retrieve a cookie set with you may use:
$cookies = explode ( ‘; ‘ , $_SERVER [ ‘HTTP_COOKIE’ ]);
$allCookies = [];

foreach( $cookies as $cookie ) $keyAndValue = explode ( ‘=’ , $cookie );
$allCookies [ $keyAndValue [ 0 ]] = $keyAndValue [ 1 ];
>

var_dump ( $allCookies );
/*
array(1) [«testing.dots»]=>
string(5) «value»
>
*/

echo $allCookies [ ‘testing.dots’ ];
?>

Источник

Cookies

Cookies are small pieces of data that can be stored on the client/browser. Once stored, they are automatically sent from the browser to the server with every request, allowing us to manipulate them using PHP.

A look at delicious cookies in real life.

Cookies are stored in a key-value pair and are used very commonly on the web, especially for things like user settings and preferences. A look at delicious cookies in real life.

Set a cookie using PHP’s built-in setcookie() function. Here’s the syntax for the function:

  • name: The name/key of the cookie.
  • value: The value of the cookie
  • expiry: The time the cookie should expire on in Unix time.
  • path: The path that this cookie should be available on.
  • domain: The domain the cookie should be available on.
  • security: The boolean indicating if the cookie should only be sent over HTTPS.

The default value for the expiry of a cookie is 0 , meaning the cookie will expire after the browser closes and terminates the session.

Now let’s look at an example of setting a cookie in PHP:

This creates a cookie set to expire in 30 days with the name city and value Miami .

A look at cookies set in PHP.

You can validate that the cookie has been set by right-clicking anywhere on the page and hitting Inspect Element (or just opening your Developer Tools). Then head on over to the Application tap at the top, then checking under the Cookies section under Storage on the left. This window displays all of our cookies and you should see the one you created here. A look at cookies set in PHP.

Now that the cookie is set, the browser will now automatically send the entire cookie with every request for as long as the cookie isn’t expired. This means we can now access the cookie on the server since it has been sent to us with the request.

PHP automatically creates an associative array with all the cookies sent in the request in the superglobal variable named $_COOKIE . This means that you can access the value of any cookie by passing in the key/name, just like you would access any associative array in PHP.

Accessing the cookie we set earlier is as easy as this:

Keep in mind that cookies can be manipulated by the user. This means that while they're useful, they cannot be trusted to hold sensitive information. This also means that you cannot expect any cookie to come from the client with a 100% certainty. Because of this, it is recommended that you first check if the cookie exists before trying to access it.

Since cookies are provided to us in an associative array, you can also display every single one like could with any associative array. This can be useful for debugging any code that uses cookies.

Print all your cookies out like so:

Deleting Cookies in PHP

You can delete a cookie by using the same function used to set them in the first place, the setcookie() function. Remember that browsers will automatically remove expired cookies. That means all you need to do is set the expiration date to any time in the past, and the browser will take care of the rest.

All you need is the name of the cookie and exactly where the cookie was set to be active, along with any time in the past:

Источник

Читайте также:  Checkbox php как проверить
Оцените статью