Zend Framework 101: Zend_Session
Writing and Reading Session Data
Once you have instantiated
Zend_Session_Namespace
, you can then write to the session using the created object. To write a new value, treat the nam of the value as a property of the object. For example, to create a session value called foo
with a value of bar
, use $session->foo = 'bar';
. You can then read the value from the session by accessing $session->foo
.
Additionally, you can use isset() to check if a session value is set.
Listing 2 shows an example of creating the namespace, writing a value, then outputting it.
Listing 2 Writing a value to session then outputting it (listing-2.php)
require_once('Zend/Session.php'); // create the session namespace $session = new Zend_Session_Namespace('identity'); // write a value to the session $session->country = 'Australia'; // output the value echo sprintf('Your country is %s', $session->country); // checking if a value is set if (isset($session->country)) { // value is set in session }
Typically though, you would write to the session on one page then access the value on the next page. For example, if you had a log in form, the identity data would be written when the user logs in, then on subsequent pages you might output a message to indicate they are logged in.
To demonstrate this, here are two PHP scripts. Note that the functionality is not complete but will hopefully demonstrate how this works.
In this example, the user submits their username and password to the
login.php
script. If the log in attempt is successful, some data is written to session and the user is redirected to members.php
.
Listing 3 Writing to session data on one script (login.php)
$username = $_POST['username']; $password = $_POST['password']; if (log_in_user($username, $password)) { require_once('Zend/Session.php'); $session = new Zend_Session_Namespace('identity'); $session->username = $username; header('Location: members.php'); exit; } else { // some error message for invalid login }
Listing 4 Reading from the session data in a subsequent script (members.php)
if (!is_logged_in()) { // some error message or redirect to log in form exit; } $session = new Zend_Session_Namespace('identity'); echo sprintf('Welcome %s!', $session->username);
While some of these methods are fictional (such as
is_logged_in()
), hopefully this demonstrates how to use session data.
No comments:
Post a Comment