[php] Arrays in cookies PHP

How is proper way to store an array in a cookie? in PHP Code example:

$number_ticket=2;
$info[7][5]=1;
$info[8][5]=1;

This question is related to php arrays security cookies

The answer is


You can also try to write different elements in different cookies. Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system. Consider explode() to set one cookie with multiple names and values. It is not recommended to use serialize() for this purpose, because it can result in security holes. Look at setcookie PHP function for more details


Cookies are basically text, so you can store an array by encoding it as a JSON string (see json_encode). Be aware that there is a limit on the length of the string you can store though.


recently i've created this code for my client, i'm using array for cookie in this code, actually this code gets recently viewed pages by user using cookies, hope it helps you...!

function curPageURL() { // get url
return 'http' . ((
!empty($_SERVER['HTTPS']) &&
$_SERVER['HTTPS'] !== 'off' ||
$_SERVER['SERVER_PORT'] == 443
) ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . (
$_SERVER['SERVER_PORT'] == 80 ? '' :  $_SERVER['SERVER_PORT']
) . $_SERVER['REQUEST_URI'];
}

$currentPage = curPageURL(); // call function
$counter = $_COOKIE['_counter']; // set counter variable

if(!$_COOKIE['_PAGES']){ // if _Pages cookie
$default = 1; // set default value to 1
setcookie("_counter",$default,time()+7200); // set counter cookie
setcookie("_PAGES[$default]",$currentPage, time()+3600); // set cookie  
}
else{ // if ! _Pages cookie 
$default = $counter+1; // set default value to +1
setcookie("_counter",$default,time()+7200); // set counter cookie
}


if(@in_array($currentPage, @$_COOKIE['_PAGES'])){ // if same url found
}
else{ // if new url found
setcookie("_PAGES[$default]",$currentPage, time()+3600); // set cookie  
}


if($_COOKIE['_PAGES']){
foreach ($_COOKIE['_PAGES'] as $value){
    echo "<a href='{$value}'>{$value}</a>";
} 
}

Try serialize(). It converts an array into a string format, you can then use unserialize() to convert it back to an array. Scripts like WordPress use this to save multiple values to a single database field.

You can also use json_encode() as Rob said, which maybe useful if you want to read the cookie in javascript.


Using serialize and unserialize on cookies is a security risk. Users (or attackers) can alter cookie data, then when you unserialize it, it could run PHP code on your server. Cookie data should not be trusted. Use JSON instead!

From PHP's site:

Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes. Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.


To store the array values in cookie, first you need to convert them to string, so here is some options.

Storing cookies as JSON

Storing code

setcookie('your_cookie_name', json_encode($info), time()+3600);

Reading code

$data = json_decode($_COOKIE['your_cookie_name'], true);

JSON can be good choose also if you need read cookie in front end with JavaScript.

Actually you can use any encrypt_array_to_string/decrypt_array_from_string methods group that will convert array to string and convert string back to same array. For example you can also use explode/implode for array of integers.

Warning: Do not use serialize/unserialize

From PHP.net

enter image description here

Do not pass untrusted user input to unserialize(). - Anything that coming by HTTP including cookies is untrusted!

References related to security

As an alternative solution, you can do it also without converting array to string.

setcookie('my_array[0]', 'value1' , time()+3600);
setcookie('my_array[1]', 'value2' , time()+3600);
setcookie('my_array[2]', 'value3' , time()+3600);

And after if you will print $_COOKIE variable, you will see the following

echo '<pre>';
print_r( $_COOKIE );
die();
Array
(   
    [my_array] => Array
        (
            [0] => value1
            [1] => value2
            [2] => value3
        )

)

This is documented PHP feature.

From PHP.net

Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system.


Just found the thing needed. Now, I can store products visited on cookies and show them later when they get back to the site.

// set the cookies
setcookie("product[cookiethree]", "cookiethree");
setcookie("product[cookietwo]", "cookietwo");
setcookie("product[cookieone]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['product'])) {
    foreach ($_COOKIE['product'] as $name => $value) {
        $name = htmlspecialchars($name);
        $value = htmlspecialchars($value);
        echo "$name : $value <br />\n";
    }
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to security

Monitoring the Full Disclosure mailinglist Two Page Login with Spring Security 3.2.x How to prevent a browser from storing passwords JWT authentication for ASP.NET Web API How to use a client certificate to authenticate and authorize in a Web API Disable-web-security in Chrome 48+ When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site? How does Content Security Policy (CSP) work? How to prevent Screen Capture in Android Default SecurityProtocol in .NET 4.5

Examples related to cookies

SameSite warning Chrome 77 How to fix "set SameSite cookie to none" warning? Set cookies for cross origin requests Make Axios send cookies in its requests automatically How can I set a cookie in react? Fetch API with Cookie How to use cookies in Python Requests How to set cookies in laravel 5 independently inside controller Where does Chrome store cookies? Sending cookies with postman