PHP113

From mi-linux
Revision as of 13:16, 19 February 2007 by In6480 (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

State and Stateless

The World Wide Web, by design, is a stateless system, in that "state" is not maintained between transactions. Basically, when you request a webpage, information is returned to you, then the connection is broken, thus no information is maintained at the server between visits.

So what?

Can you imagine trying to make an eCommerce solution where you can't store information between pages - anything you add to a "basket" would be lost when you move to the next page. How can we create a "pseudo-state" between visits? There are two possible solutions, and a combination of these should provide a solution.

Cookies

Cookies are small variables held in the web client (browser) and can hold information that the server can access. When you access a given server (amazon.com) for example, the server can write a small file to your computer holding some variables and their corresponding values, assuming you have set your web browser privileges to allow cookies. When you revisit the server, your cookies are sent back to server.

A simple cookie example

create this file, and save it as "page1.php" - COPY IT and save it as page2.php, page3.php as well

 <html>
   <head>
     <title>Cookie Test</title>
   </head>
   <body>
     <h1>The Cookie Example...</h1>
     <?
       if (isset($_COOKIE["numberOfPagesViewed"]))
       {
         echo "<p>You have visited ".$_COOKIE["numberOfPagesViewed"]." pages so far</p>";
         $_COOKIE["numberOfPagesViewed"]++;
       }
       else
       {
         echo "<p>this is your first page viewed</p>";
         $_COOKIE["numberOfPagesViewed"]=1;
       }
     ?>
   </body>
 </html>

point your browser to page1.php, then to page2, then page3, then back to page1, etc. See how the counter increments?