minte9
LearnRemember / PHP



Cookies

Allows your application to store a small text file on client Web browser. If you want to set cookie for another domain, it can not be done.
 
setcookie('hide_menu', '1'); // Set a cookie on the client
setcookie('hide_menu', '1', 3600); // expiration time - 1 hour

if ($_COOKIE['hide_menu'] == 1) {
    echo 'Hide Menu';
}

Values

Cookies values must be scalar, not arrays. To delete a cookie, set time negative.
 
setcookie('hide_menu', array()); //expects parameter 2 to be string
 
setcookie("hide_menu", false, -3600);
You can create cookie arrays using the same array. Keep in mind that the amount of storage available is severely limited, use sessions instead.
 
setcookie('test[0]', "foo");
setcookie('test[1]', "bar");

Arguments

You can set different cookie arguments.
 
setcookie('hide_menu', '1', 86400, '/path/', 'www.example.com', 1); 

    // where cookie will be accesible - path
    // allowed domain
    // the browser can only send cookie in case of HTTPS
    // expiration time one day






Questions and answers




How do you set a cookie?

  • a) setcookie('hideMenu', 1);
  • b) $_COOKIE['hideMenu'] = 1;

Can you do this?

  • a) Yes, cookie can be created using arrays
  • b) No, cookie accepts only scalar values

What happens when a cookie is set?

  • a) cookie is sent to the SERVER
  • b) cookie is sent to the BROWSER

When is the $_COOKIE array populated?

  • a) At the next request
  • b) After the data are passed to the PHP interpreter

How you delete a cookie?

  • a) unset($_COOKIE['xx']);
  • b) setcookie('xx', false, -3600);


References