Put an Array in a cookie in PHP

1

I have a query that returns me the hits of the user who just logged in. I need to turn them into an array and store them in a session and a cookie. Here is the code:

//ARMAZENA AS PERMISSOES DO PERFIL DO USUARIO
if($sql_permissoes->rowCount() > 0){
    $permissao_visualizacao = array();
    $permissao_alteracao        = array();
    foreach ($sql_permissoes as $sql_permissoes_row) {
        $permissao_visualizacao[]   = $sql_permissoes_row["url_localizacao"];
        $permissao_alteracao[]      = $sql_permissoes_row["permite_alteracao"];
    }
}

$_SESSION["ged.permissao.visualizacao"] = $permissao_visualizacao;
$_SESSION["ged.permissao.alteracao"]    = $permissao_alteracao;
setcookie("ged.permissao.visualizacao", $permissao_visualizacao, mktime(0, 0, 0, date("m"), date("d")+5, date("Y")) );
setcookie("ged.permissao.alteracao", $permissao_alteracao, mktime(0, 0, 0, date("m"), date("d")+5, date("Y")) );

But in the setcookie lines I get the following message:

Warning: setcookie() expects parameter 2 to be string, array given.

What is the most recommended method of doing this?

    
asked by anonymous 06.04.2015 / 14:44

3 answers

0

If your cookie name has any point , using setcookie , it becomes underline .

In my example, since I was storing the cookie ged.permissao.visualizacao , I got it as ged_permissao_visualizacao and it worked.

link

Thanks @GeBender for the help.

    
06.04.2015 / 20:27
1

A good alternative is to serialize the array, that is, to convert to a string: link

setcookie("ged.permissao.visualizacao", serialize($permissao_visualizacao), mktime(0, 0, 0, date("m"), date("d")+5, date("Y")) );
setcookie("ged.permissao.alteracao", serialize($permissao_alteracao), mktime(0, 0, 0, date("m"), date("d")+5, date("Y")) );

To read the cookie you should use unserialize: link

$permissao_visualizacao = unserialize($_COOKIE['ged_permissao_visualizacao']);
$permissao_alteracao = unserialize($_COOKIE['ged_permissao_visualizacao']);

I hope I have helped.

    
06.04.2015 / 14:51
0

As the error suggests, cookie data must be in the string format. More importantly, you should not store actual data in a cookie because the user can edit them.

$permissao_visualizacao = unserialize($_COOKIE['ged.permissao.visualizacao']);

session_start () should be called before anything is output on every page.

If the error persists try to use a third parameter in the cookie set setcookie('email', $first_email, time()+60*60*24*100);

    
06.04.2015 / 14:53