10.4 Setting and Getting Cookie Parameters


You want to get or set cookie parameters at runtime instead of in your php.ini file.

Technique

To set parameters, use the session_set_cookie_params() function, which enables you to set the lifetime of the cookie, the path of the cookie, and the domain of the cookie:

 <?php session_set_cookie_params(time()+8600,                           '/cookiepath',                           'designmultimedia.com'); ?> 

To get the session cookie parameters, use the session_get_cookie_params() function:

 <?php $cookie_params = session_get_cookie_params(); print "Cookie Lifetime:  $cookie_params[lifetime]\n<br>\n        Cookie Path:      $cookie_params[path]\n<br>\n        Cookie Domain:    $cookie_params[domain]"; ?> 

Comments

The session_set_cookie_params() function has the following syntax:

 int session_set_cookie_params(int lifetime,[ string path, [string domain]]); 

It enables you to modify at runtime the cookie parameters in the php.ini file. The lifetime parameter is how long until the cookie will expire. The optional path parameter is the path where the cookie will be stored and the domain is the domain that will be allowed to access the cookie. The function returns 1 on success and on failure; if no arguments are given, the function returns an array of the current settings.

Even though all these parameters can be set in the php.ini file, it often helps to be able to modify session options at runtime, especially when dealing with something as specific as cookies.

The session_get_cookie_params() function returns an array containing the lifetime, path, and domain settings of the cookie, meaning that you can use the session_ get_cookie_params() function to make sure that the session_set_cookie_params() function actually succeeded:

 <?php $lifetime = time() + 8600; $path      = '/cookiepath'; $domain = 'php.net'; if (session_set_cookie_params ($lifetime, $path, $domain)) {     $cookie_params = session_get_cookie_params ();     if ($cookie_params[lifetime] == $lifetime &&         $cookie_params[path] == $path           &&         $cookie_params[domain] == $domain) {         print "Congrats, the session_set_cookie_params()";         print " function really worked";     } } ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net