Request Object

Going back to the MVC life cycle, after the controller finishes processing with no errors, it initializes the user interface (UI) that the user will see, otherwise known as the view. Because the view is a critical component for the controller, the controller automatically creates three objects for immediate use:

• ViewRenderer

The Request object is covered in this section (you'll look at the ViewRenderer and the Response object in Chapter 4).

The Request object handles all incoming user data or any data sent from the user's browser to the application code. This data is always in the form of a POST submission, query submitted data, or raw header data.

Query data comes in the form of a URL such as http://localhost/account?u=armando, where u=armando is the data you want to process. POST data is form-submitted content. The request object allows you to fetch this data and manipulate it within the code. You'll expand on the sign-up form and add the artist form for this example.

Let's start with the AccountController. You already have the newAction() method, which deals with requests for the sign-up form, but you need an action to process any incoming form submissions. This requires an action in the AccountController.php file, so you'll be using the successAction() method, as shown in Listing 3-12. You want to learn how Zend Framework handles incoming data, so you'll fetch all incoming parameters.

Listing3-12. AccountController.php - updated successAction

* Process the account form.

public function successAction() {

$email = $this->_request->getParam('email'); $username = $this->_request->getParam('username'); $password = $this->_request->getParam('password');

//Save the user into the system.

As you can tell from the preceding code, you added a few lines into the successAction() method. The new lines of code allows you to capture all incoming user data by using the request object's getParam() method. Here you capture three parameters from an XHTML form you will create in Chapter 4, containing three form input fields for the new.ptml page and store the data inside three variables: $email, $username, and $password. At the moment you won't be doing much with this data, but it's nice to have a foundation that allows you to successfully capture user data.

Expanding on the getParam() method, it accepts a parameter, which is the name of the parameter you want to capture. The form input field name values specified were email password and username. These unique identifiers are the parameters for the getParam() function. Easy, right? Yes, but there is a big security risk using this method, and the best way to understand why is to analyze how Zend Framework treats superglobal data.

Superglobal Data in Zend Framework

You've used superglobal variables because they are part of PHP. COOKIE, SERVER, ENV, GET, and POST are the types of superglobal variables that Zend Framework uses and these are also the variables that the request object fetches.

Zend Framework uses a set way to capture these variables. Following is the order in which Zend Framework captures these variables:

2. POST

3. COOKIE

4. SERVER

Because getParam() does not distinguish whether you want to fetch POST data or GET data, a malicious user can easily change any POST data by modifying the URL to pass in a GET value. To counteract this behavior, Zend Framework created a list of getters (see Table 3-1).

Request Object's Getters

Suppose that you attempted the old tried-and-true method of creating a simple form for your users and you created that millionth form $_POST code on your PHP script. Let's use the secure Zend Framework getter now by updating AccountController successAction(), as shown in Listing 3-13.

Listing 3-13. AccountController.php

* Account Controller

class AccountController extends Zend_Controller_Action {

public function init() {

/* Initialize action controller here */

public function indexAction() {

// action body

* Process the account form.

public function successAction() {

$email = $this->_request->getPost("email"); $username = $this->_request->getPost("usemame"); $password = $this->_request->getPost("password");

//Save the user into the system.

* Display the form for signing up.

public function newAction() {

* Activate Account. Used once the user

* receives a welcome email and decides to authenticate

* their account.

public function activateAction() {

In this example, successAction() takes the user's information that was previously entered in the form using the getPost() method, which retrieves only POST data.

The getPost() method allows you to fetch only data passed in using a POST request and nothing else. This is different from the getParam() method that allows users to use POST or query data. But sometimes you need to have query data such as account validation or a parameter that helps you fetch paginated data.

Processing a GET Submission

POST data is nice, but what if you require the user to pass in a variable string through the URL? A good example is a user authenticating the account after signing up as a new user by clicking a link in an e-mail message (for example, http://localhost/account/activate?email=test@test.com or a user paginating through a list of images in your search result that uses the URL http://localhost/account/results?x=20 to determine which result index to start from). Apart from getParam(), how do you retrieve those values?

For this example, you'll update the activateAction() method in the AccountController.php file, as shown in Listing 3-14. The action will retrieve the e-mail address that needs to be activated from the requested URL clicked by the user. You'll fetch the data, but not fully activate the account just yet.

Listing3-14. AccountController.php: UsinggetQuery

* Account Controller

class AccountController extends Zend_Controller_Action {

public function init() {

/* Initialize action controller here */

public function indexAction() {

// action body

* Process the account form.

public function successAction() {

$email = $this->_request->getPost("email"); $username = $this->_request->getPost("username"); $password = $this->_request->getPost("password");

//Save the user into the system.

* Display the form for signing up.

public function newAction() {

* Activate Account. Used once the user

* receives a welcome email and decides to authenticate

* their account.

public function activateAction() {

//Fetch the email to update from the query param 'email' $emailToActivate = $this->_request->getQuery("email");

//Check if the email exists //Activate the Account.

Compare the POST and GET examples; there isn't much difference. In both examples, you use the request object, but in this example you use the getQuery() method to retrieve all incoming query variables.

Other Request Object Features

The request object doesn't stop there when it comes to fetching user data. It also allows you to fetch all raw POST and header information. Take a look at Table 3-1 for more information on the type of operations the request object can handle.

Table 3-1. Request Object Operations

Function

What Does It Do?

What Does It Return?

getParam(String key)

Retrieves an individual parameter to be accessible by the action.

Returns the value for the parameter key specified.

getParams()

Retrieves multiple parameters to be accessible by the action.

Returns an associative array of key/value pairs for multiple parameters of a request object.

getPost(String key)

Retrieves an individual parameter to be accessible by the action.

Returns the value for the parameter key specified.

getQuery(String key)

Retrieves an individual GET parameter to be accessible by the action.

Returns the value for the parameter key specified.

Zend Request Type Checkers

Besides allowing you to retrieve information sent to you by a user's request or a process, the request object can also determine the type of request that was made. This is great if you want to validate whether the request was a POST request or an Ajax request. Using request-type checkers reduces the chances of malicious users trying to manipulate POST variables with GET variables or send a POST to a process when your code expects an Ajax XmlHttpRequest call.

Checking Whether the Request Is a POST

Zend Framework's request object comes equipped with the method isPost() that you can use to test for POST data, as shown in Listing 3-15.

Listing3-15. AccountController.php: Using isPost()

* Account Controller

class AccountController extends Zend_Controller_Action {

public function init() {

/* Initialize action controller here */

public function indexAction() {

// action body

* Process the account form.

public function successAction() {

//Check if the submitted data is POST type if($this->_request->isPost()){

$email = $this->_request->getPost("email"); $username = $this->_request->getPost("username"); $password = $this->_request->getPost("password");

//Save the user into the system.

throw new Exception("Whoops. Wrong way of submitting your information.");

* Display the form for signing up.

public function newAction() {

* Activate Account. Used once the user

* receives a welcome email and decides to authenticate

* their account.

public function activateAction() {

//Fetch the email to update from the query param 'email' SemailToActivate = $this->_request->getQuery("email");

//Check if the email exists //Activate the Account.

Listing 3-15 expands the successAction() method to validate that the incoming request was a POST type. The important section in this example is the if statement. Here you use the default request object and its isPost() method. If the incoming request is not a POST type, the user sees an error message: "Whoops. Wrong way of submitting your information." The script then stops executing.

Checking for a GET Request

Checking for a GET request type is straightforward and requires you to change only the if statement to read as follows:

The new function that uses a GET request type looks like this:

//Action #1 - Sign up for an account form. public function successAction(){

//Check if the submitted data is GET type if($this->_request->isGet()){

$email = $this->_request->getQuery("email"); $username = $this->_request->getQuery("username"); $password = $this->_request->getQuery("password");

//Save the user into the system.

throw new Exception("Whoops. Wrong way of submitting your information.");

Checking for an Ajax Call Request

So you're tired of creating only one-dimensional POST and GET forms; you want to sink your teeth into a little asynchronous calling. You pop open that browser and start looking up for a nice Ajax framework. After you choose your framework, you might wonder how you can stitch the Ajax calls to Zend Framework. I won't cover the setup of an Ajax call because there are too many good Ajax frameworks out there: jQuery, Prototype, Scriptaculous, and Dojo. So I will cover only the back-end script that is called by the Ajax function.

Using the same successAction() function, you can expand it by allowing the script to accept only Ajax requests by checking for the XmlHttpRequest type (see Listing 3-16).

Listing 3-16. AccountController.php: Checking for Ajax Calls

public function successAction() {

//Check if the submitted data is an Ajax call if($this->_request->isXmlHttpRequest()){

$email = $this->_request->getQuery("email"); $username = $this->_request->getQuery("username"); $password = $this->_request->getQuery("password");

//Save the user into the system.

throw new Exception("Whoops. Wrong way of submitting your information.");

The preceding code changed the GET and POST versions only slightly. The bold line shows the new Request object method isXmlHttpRequest(). This method enables the script to check whether the incoming request was an Ajax call. The method returns true if it was an Ajax call and false if not. Depending on your Ajax framework, you can also change the way the data is sent to the script, either by a POST or a GET submission. In that case, you can check the incoming data using the isPost() or isGet() method instead of the more general isParam() method, which is an additional method of checking for submitted data. The isParam() function checks whether there was any data in any submitted variable.

Request Type Checkers

Table 3-2 contains a complete list of checkers the request object allows you to use. Table 3-2. Request Object Checkers

Function

What Does It Do?

What Does It Return?

isPost() Checks whether the incoming request type is a POST request.

isGet() Checks whether the incoming request type is a GET request.

isPut() Checks whether the incoming header request is a PUT request.

isDelete() Checks whether the incoming header request is a DELETE request.

isHead() Checks whether the incoming request contains header information isOptions() Checks whether the incoming request is an OPTIONS request isXmlHttpRequ Checks whether the incoming request est() type is a XmlHttpRequest, which is used in

JQuery, Mochikit, Yahoo! UI Library, and any libraries with core Prototype foundations.

Returns true if it is a POST type; otherwise, returns false.

Returns true if it's a GET request type; otherwise, returns false.

Returns true if it's a PUT header request; otherwise, returns false.

Returns true if is a DELETE header request; otherwise, returns false.

Boolean.

Boolean.

Returns true if it's an Ajax call; otherwise, returns false.

Now that you've seen the basics of controllers and views, it's time to see how to deal with situations in which things don't go according to plan.

0 0

Post a comment

  • Receive news updates via email from this site