PHP parse json array with cookies and set all cookies from it

454 Views Asked by At

I need save all cookies from domain in mysql table and then get it from mysql and then set for user.

Here's example:

$cookies = json_encode($_COOKIE);
//save $cookies to mysql 
//...get it from mysql in $mysqlCookies

And now I need setcookie($cookie_name, $cookie_value, ...)
How can I parse json $mysqlCookies in 2 variables, like $cookie_name and $cookie_value, which should save name and value from $mysqlCookies?

2

There are 2 best solutions below

0
On BEST ANSWER

You need json_decode().

$thecookies = json_decode($mysqlCookies);

foreach($thecookies as $name => $value) {
    setcookie($name, $value, time()+3600); // expires 1 hour..
}

The above will set your cookies properly as you require.

0
On

I would recommend using serialize/unserialize insted of json_encode/json_decode since the cookies are just transported between PHP and the database.

Saving to database

$cookies = serialize($_COOKIE);
// Write the $cookies string to a column in the database

Reading from database

$cookies = unserialize($cookieColumnFromDatabase)

foreach ($cookies as $cookieName => $cookieValue) {
    setcookie($cookieName, $cookieValue);
}