July 08, 2020, 07:50:53 PM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
   Home   Help Search Login Register  
Pages: [1]
Author Topic: how cookies work with examples  (Read 17216 times)
Hero Member
Posts: 788

« on: January 02, 2007, 07:55:57 AM »

Cookie is a bit of information stored by the surfer's browser (i.e. cookies are client-side data).

Cookie can hold any information, but usually applications use cookies to store user's specific information (login, encrypted password, last visited date, etc.).

PHP can read cookies from user's browser, and set them when needed.

Use setcookie php function to set a cookie.
Use $_COOKIE variable (array) to retrieve a cookie.

How it works:
1) initial state, just before user opens some-page.php in the browser.
          $_COOKIE array is empty at this point.
          No cookie in the browser at this point.
2) some-page.php sets cookie named "my-cookie" via setcookie php function, and cookie goes to the browser along with page content
          $_COOKIE array is still empty at this point.
          Browser has cookie "my-cookie" at this point.
3) next time user opens some-page.php (or after refresh)
          $_COOKIE array now contains "my-cookie".
          Browser still has cookie "my-cookie".

This code will not work. setcookie does not populate $_COOKIE array. login cookie will be added to the $_COOKIE array only after page is refreshed (item 3 above). You will have to manually populate $_COOKIE array if you need to check cookie before page is refreshed.

$_COOKIE['login'] = 'my-nick-name';
Note: $_COOKIE array changes will not be visible after page is refreshed if you change it directly ($_COOKIE['bbb'] = 'some-value').

Lets assume we have this code in the program:

// third parameter is expire-time in seconds. Set to false in order to have cookie expire when browser is closed.
// forth parameter is the path on the server in which the cookie will be available on.
setcookie('login','my-nick-name', false, '/');
setcookie('password','pass1', false, '/login/');
setcookie('password','pass2', false, '/signup/');

After above code is run:

  will see: login => my-nick-name,  password => pass1
  will see: login => my-nick-name,  password => pass2

Note how sub-folders see cookies from parent folders. Also remember that php-examples.com will not see a cookie set for www.php-examples.com.

Avoid redirects after setting a cookie. It would not work on some servers. IIS is known to have problems with that.

// cookie may be lost in this case
header('Location: http://www.example.com/');

No output allowed before setcookie. Otherwise you'll get cannot modify header information, headers already sent error. Even one space or new line character before setting cookie would cause this problem.

Pages: [1]
Jump to:  

Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC