chitika Ad

Saturday, 1 March 2014

Zend Framework 101: Zend_Session

Zend Framework 101: Zend_Session

Removing Session Data

To remove a value from a session, use PHP's unset() function on the object property. This is demonstrated in Listing 5.
Listing 5 Removing a value from a session namespace (listing-5.php)
<?php
    require_once('Zend/Session.php');
 
    $session = new Zend_Session_Namespace('identity');
    unset($session->username);
?>
In some cases you might want to remove all data in a namespace. You can do this either by looping over all values in the namespace and calling unset() on each one, or you can use theZend_Session::namespaceUnset(). This method accepts the name of the namespace as its only argument, as demonstrated in Listing 6.
Listing 6 Removing an entire namespace from a session (listing-6.php)
<?php
    require_once('Zend/Session.php');
 
    Zend_Session::namespaceUnset('identity');
?>
You can destroy the entire current session using the Zend_Session::destroy() static function.

Zend Framework 101: Zend_Session

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)
<?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)
<?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)
<?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.

Zend Framework 101: Zend_Session

Zend Framework 101: Zend_Session

Creating Session Namespaces

The Zend Framework provides advanced session handling using the Zend_Session component. Using this component, you no longer need to access PHP's $_SESSION global variable.
Note: In fact, you should not access $_SESSION at all when using Zend_Session.
Zend_Session uses namespaces to store your session data. That is, when you want to read or write session data you must first specify a namespace. This allows you to easily store different session data without worrying too much about other values stored in the session.
You create a new session namespace by instantiating the Zend_Session_Namespace class. The first argument to the constructor is the name of the namespace. Listing 1 shows an example of this.
Listing 1 Creating a namespace for storing user identity data (listing-1.php)
<?php
    require_once('Zend/Session.php');
 
    $session = new Zend_Session_Namespace('identity');
?>
We can now read or write session data in the identity namespace using the $session variable. I will show you how to do this shortly.
Note also that you do not need to manually start sessions (using the session_start() function) as you might have in the past when using sessions in PHP. Instantiating this class takes care of this for you.
Note: As always, session handling must be performed prior to performing any output. This is easy to achieve if you're using Model-View-Controller (or similar – that is, performing any required processing in your scripts prior to output), or if you use output buffering. If you want to force sessions to start earlier in your script without creating a specific namespace, you can call Zend_Session::start() instead.
Internally, the above code will be accessing data in the $_SESSION['identity'] variable. You should never access this directly.

Zend Framework 101: Zend_Session

Zend Framework 101: Zend_Session

This article is part of the series “Zend Framework 101”. The Zend Framework 101 series covers many components that make up the Zend Framework in easy to understand articles.. Read more about Zend Framework 101...

Introduction

In this article I will introduce you to the Zend_Session component of the Zend Framework. This component is built upon PHP's native session-handling functionality, making it easier to manage session data, as well as providing more advanced features.
Firstly I will show you how to read and write data using Zend_Session, then I will show you how to implement a "remember me" feature for logging-in users on your web site.
This article requires Zend Framework, downloadable from http://framework.zend.com. At time of writing, the current version of Zend Framework is 1.9.6.

Zend Framework 101: Zend_Service_Amazon_S3

Zend Framework 101: Zend_Service_Amazon_S3

Summary

In this article I introduced you to the Zend_Service_Amazon_S3 component of the Zend Framework, used for managing data on the Amazon S3 (Simple Storage Service) component of Amazon Web Services (AWS).
First I showed you how to access AWS. Next I introduced you to buckets and how to manage them. Next I showed you how to manage data in your buckets. Finally, I showed you how to use the data you've stored on Amazon S3.
Further reading:

Other Options

Zend Framework 101: Zend_Service_Amazon_S3

Zend Framework 101: Zend_Service_Amazon_S3

Using Objects Stored in Amazon S3 Buckets

Finally, let's look at how other users can access files you store in your Amazon S3 buckets. The name of the bucket maps directly to the following domain name to the following web addresses:
  • http://[bucketName].s3.amazonaws.com/[objectName]
  • http://s3.amazonaws.com/[bucketName]/[objectName]
Using our previous examples from this article, you can access the my-file.txt file at the following URLs:
  • http://phpriot-test-bucket.s3.amazonaws.com/my-file.txt
  • http://s3.amazonaws.com/phpriot-test-bucket/my-file.txt
If we didn't set the permissions to be publicly readable, then it would not be possible for others to access your files.
You can now link to these files directly from your web pages, rather than hosting your files yourself. The following listing demonstrates how you might achieve this. It uses Amazon S3 for CSS, images, and for a file download link.
Listing 12 Using your Amazon S3 bucket on your web site (use-cdn.php)
<?php
    $bucketName = 'my-company-bucket';
    $cdnUrl = 'http://' . $bucketName . '.s3.amazonaws.com';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Sample Amazon S3 CDN Usage Page</title>
        <link rel="stylesheet"
              href="<?php echo $cdnUrl ?>/css/styles.css"
              type="text/css"
              media="all" />
    </head>
    <body>
        <div>
            <img src="<?php echo $cdnUrl ?>/images/logo.png" alt="My Logo" />
        </div>
        <div>
            <a href="<?php echo $cdnUrl ?>/assets/profile.pdf">
                Download company profile
            </a>
        </div>
    </body>
</html>

Zend Framework 101: Zend_Service_Amazon_S3

Zend Framework 101: Zend_Service_Amazon_S3

Reading Objects

The methods used to retrieve objects from a bucket are getObject() and getObjectStream(). You can usegetObject() to return the object data into a PHP variable, while getObjectStream() is most useful for writing an object directly to your local filesystem.
For now, we'll just look getObject(). This method accepts as its only argument the name of the object, and returns the data found in the object. If the object can't be returned then false is returned instead.
The following listing demonstrates combining a call to getInfo() and getObject() so you can send the file back to the end-user. It retrieves the information about the file first so it can determine the mime type and file size.
Listing 11 Sending an object directly from an S3 bucket (get-object.php)
<?php
    require_once('Zend/Service/Amazon/S3.php');
 
    $awsKey       = '[your key]';
    $awsSecretKey = '[your secret key]';
 
    $s3 = new Zend_Service_Amazon_S3($awsKey, $awsSecretKey);
 
    $bucketName = 'phpriot-test-bucket';
    $objectName = $bucketName . '/my-file.txt';
 
    $info = $s3->getInfo($objectName);
 
    if (is_array($info)) {
        header('Content-type: ' . $info['type']);
        header('Content-length: ' . $info['size']);
 
        echo $s3->getObject($objectName);
    }
    else {
        header('HTTP/1.0 404 Not Found')
    }
?>
This example is really just for demonstration purposes only. If you were using Amazon S3 as a content delivery network it would be completely redundant (not to mention much slower) to read in the files and send to users as requested.