presentation-sessions-cookies-php-5-1200979079583482-4

Views:
 
     
 

Presentation Description

No description available.

Comments

Presentation Transcript

Sessions and Cookies: 

Sessions and Cookies

How to maintain state in a stateless web: 

How to maintain state in a stateless web

What is meant by state?: 

What is meant by state? To maintain state means the ability to retain values of variables and to keep track of users who are logged into the system.

Methods for maintaining state : 

Methods for maintaining state Cookies Sessions Passing [hidden] variables

What is a cookie?: 

What is a cookie? Cookies are simple text strings of the form of name=value which are stored persistently on the client’s machine. A URL is stored with each cookie and it is used by the browser to determine whether it should send the cookie to the web server.

Cookie Example: 

Cookie Example <?php $count++; setCookie(“count”, $count); ?> Welcome! You’ve seen this site <?php print($count . ($count == 1 ? “ time!” : “ times!”)); ?>

Common Pitfalls: 

Common Pitfalls Can’t call setCookie() after output has been sent to the browser Can’t have more than 20 cookies/server Cookies ONLY persist until the browser closes UNLESS you specify an expiry date: set Cookie(“name”, $value, time() + 3600);

Sessions: 

Sessions Sessions are just like cookies, except they store the user’s data on the web server. Every request has a unique session id. Sessions are more reliable than cookies.

Session Example: 

Session Example ?php // start the session session_start(); // Get the user's input from the form $name = $_POST['name']; // Register session key with the value $_SESSION['name'] = $name; ?>

Destroying a Session: 

Destroying a Session <?php // start the session session_start(); $_SESSION = array(); session_destroy(); if($_SESSION['name']) { print "The session is still active"; } else { echo "Ok, the session is no longer active! <br />"; } ?>