Search code examples
phpmysqljsoncookiessetcookie

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


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?


Solution

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