PHP

Building Applications That Keep State

Applications sometimes need to use the result of one request when processing another. For example, a request that adds an item to a shopping cart needs to be remembered when the request is made to create the order. In other words, the state of the application needs to be stored between HTTP requests. There are two ways to achieve this: variables that hold the state can be stored in the browser and included with each request or variables can be stored on the server.

Most of this tutorial is devoted to the second alternative, where the middle tier stores and manages the application state using sessions. However, in this section we briefly discuss solutions that store state in the client tier. One technique described in this section is the use of cookies. While cookies can store state in the client tier, they are also used in middle-tier session management, as described later in this tutorial.

Managing State in the Client Tier

Data sent with the GET or POST methods can include the application state with each HTTP request. An illustration of this approach can be seen in the previous and next browsing features developed in tutorial 5. In this example, there are two pieces, or states, that need to be considered when a page is browsed: the query parameters the user provided and which page should be displayed.

The solution developed in tutorial 5 encodes the query and an offset as an embedded link. An example URL that displays the fourth page of results may be as follows:

http://localhost/example.5-10.php?regionName=All&offset=40

This solution allows navigation through large search result sets. Similar solutions are used in the URLs generated to jump between the results pages of web search engines such as Google or Altavista. Cookies can be used for the same purpose.

Encoding the variables that hold state with each HTTP request increases the amount of data that has to be transmitted over the Web, and when data is encoded using the GET method, applications can generate long URLs. While HTTP doesn't restrict the length of URLs, some older browsers and proxy servers do enforce limits.

When state variables are encoded as part of the URL, or even when they are included as cookies, it is possible for the user to change the values that are sent with the request. For example, a user can enter the following URL manually if she wants to see the records starting from row #7 in the result set:

http://localhost/example.5-10.php?regionName=All&offset=7

Changing the offset in a results page is harmless, but changing the item price of a bottle of wine is more serious. As discussed in tutorial 6 and tutorial 7, an application can't rely on data that is sent from the browser.

by BrainBellupdated
Advertisement: