Managing State: 5.1 The Problem of State in Web Applications
Managing State: 5.1 The Problem of State in Web Applications
Module – 5 Managing State, The Problem of State in Web Applications, Passing Information via Query
Strings, Passing Information via the URL Path, Cookies, Serialization, Session State, HTML5 Web
Storage, Caching, Advanced JavaScript and jQuery, JavaScript Pseudo-Classes, jQuery Foundations,
AJAX, Asynchronous File Transmission, Animation, Backbone MVC Frameworks, XML Processing
and Web Services, XML Processing, JSON, Overview of Web Services. 10 Hours
MODULE 5
Managing State
5.1 The Problem of State in Web Applications
Problem: How can one request share information with another request?
Single-user desktop applications do not have this challenge at all because the program information
for the user is stored in memory (or in external storage) and can thus be easily accessed throughout the
application.
Unlike the unified single process that is the typical desktop application, a web application consists of
a series of disconnected HTTP requests to a web server where each request for a server page is
essentially a request to run a separate program, as shown in Figure 13.1.
Furthermore, the web server sees only requests. The HTTP protocol does not, without programming
intervention, distinguish two requests by one source from two requests from two different sources, as
shown in Figure 13.2.
Consider the scenario of a web shopping cart, as shown in Figure 13.3. In such a case, the user (and
the website owner) most certainly wants the server to recognize that the request to add an item to the
cart and the subsequent request to check out and pay for the item in the cart are connected to the same
individual.
5.2 Passing Information via Query Strings
A web page can pass query string information from the browser to the server using one of the two
methods: a query string within the URL (GET) and a query string within the HTTP header (POST).
Figure 13.4 reviews these two different approaches.
We can try doing our own rewriting. Let us begin with the following URL with its query string
information:
www.somedomain.com/DisplayArtist.php?artist=16
One typical alternate approach would be to rewrite the URL to:
www.somedomain.com/artists/16.php
Notice that the query string name and value have been turned into path names.
One could improve this to make it more SEO friendly using the following:
www.somedomain.com/artists/Mary-Cassatt
5.4 Cookies
Cookies are a client-side approach for persisting state information. They are name=value pairs that are
saved within one or more text files that are managed by the browser.
Sites that use cookies should not depend on their availability for critical features
The user can delete cookies or tamper with them
There are limitations to the amount of information that can be stored in a cookie (around 4K) and to the
number of cookies for a domain (for instance, Internet Explorer 6 limited a domain to 20 cookies).
A session cookie has no expiry stated and thus will be deleted at the end of the user browsing session.
Persistent cookies have an expiry date specified; they will persist in the browser’s cookie file until the
expiry date occurs, after which they are deleted.
Limitations of Cookies:
ly the product identifier but also the product price in the cart. Unfortunately, the site then used the price in the cookie in the ch
Cookies in PHP are created using the setcookie() function and are retrieved using the
$_COOKIES superglobal associative array.
MENTofCSE,KSSEM Page 6
It is important to note that cookies must be written before any other page output.
In addition to being used to track authenticated users and shopping carts, cookies can implement:
“Remember Me” checkbox on login forms, which relies on the use of a persistent cookie
Store user preferences. For instance, some sites allow the user to choose their preferred site color scheme
or their country of origin or site language.
Track a user’s browsing behavior. Some sites will store a pointer to the last requested page in a cookie;
this information can be used by the site administrator as an analytic tool to help understand how users
navigate through the site.
5.5 Serialization
Serialization is the process of taking a complicated object and reducing it down to zeros and ones for
either storage or transmission.
In PHP objects can easily be reduced down to a binary string using the serialize() function.
The string can be reconstituted back into an object using the unserialize() method.
The output of calling serialize($picasso) is:
C:6:"Artist":764:{a:7:{s:8:"earliest";s:13:"Oct 25,
1881";s:5:"firstName";s:5:"Pablo";s:4:"lastName";s:7:"Picasso";s:5:"birthDate";s:13:" Oct 25,
1881";s:5:"deathDate";s:11:"Apl 8, 1973";s:5:"birthCity”;s:6:"Malaga";s:5:"works";
a:3:{i:0;C:8:"Painting":134:{a:2:{s:4:"size”;a:2:{i:0;d:7.7999999999999998;i:1;d:3.5;}s:
7:"artData";s:54:"a:2:{s:4:"date";s:4:"1937";s:4:"name";s:8:"Guernica";}";}}i:1;C:9:"Sc ulpture”:186:{a:2:
{s:6:"weight";s:8:"162 tons";s:13:"paintingData";
s:133:"a:2:{s:4:"size";a:1:{i:0;d:15.119999999999999;}s:7:"artData";s:53:”a:2:{s:4:"da
te";s:4:"1967";s:4:"name";s:7:"Chicago";}";}";}}i:2;C:5:"Movie":175:{a:2:{s:5:"media";
s:8:"file.avi";s:13:"paintingData";s:113:"a:2:{s:4:"size";a:2:{i:0;i:32;i:1;i:48;}s:7:"artDa
ta";s:50:"a:2:{s:4:"date";s:4:"1968";s:4:"name";s:4:"test";}";}";}}}}}
If the data above is assigned to $data, then the following line will instantiate a new object identical to
the original:
$picassoClone = unserialize($data);
Application of Serialization
Since each request from the user requires objects to be reconstituted, using serialization to store and
retrieve objects can be a rapid way to maintain state between requests.
At the end of a request you store the state in a serialized form, and then the next request would begin by
deserializing it to reestablish the previous state.
All modern web development environments provide some type of session state mechanism. Session
state is a server-based state mechanism that lets web applications store and retrieve objects of any type
for each unique user session.
Session state is ideal for storing more complex objects or data structures that are associated with
a user session. • In PHP, session state is available to the via the $_SESSION variable • Must use
session_start() to enable sessions.
How does state session work?
Sessions in PHP are identified with a unique 32byte session ID. This is transmitted back and forth
between the user and the server via a session cookie
For a brand new session, PHP assigns an initially empty dictionary-style collection that can be used to
hold any state values for this session.
When the request processing is finished, the session state is saved to some type of state storage
mechanism, called a session state provider
When a new request is received for an already existing session, the session’s dictionary collection is filled
with the previously saved session data from the session state provider.
Session Storage and Configuration
It is possible to configure many aspects of sessions including where the session files are saved. The
decision to save sessions to files rather than in memory (like ASP.NET)
addresses the issue of memory usage that can occur on shared hosts as well as persistence between
restarts.
Inexpensive web hosts may sometimes stuff hundreds or even thousands of sites on each machine.
Server memory may be storing not only session information, but pages being executed, and caching
information.
Higher-volume web applications often run in an environment in which multiple web servers (also called
a web farm) are servicing requests.
In such a situation the in-process session state will not work, since one server may service one request
for a particular session, and then a completely different server may service the next request for that
session
Just as there were two types of cookies, there are two types of global web storage:
The localStorage object is for saving information that will persist between browser sessions.
The sessionStorage object is for information that will be lost once the browser session is finished.
Using Web Storage
There are two ways to store values in web storage: using the setItem() function, or using the property
shortcut (e.g., sessionStorage.FavoriteArtist).
Why Would We Use Web Storage?
A better way to think about web storage is not as a cookie replacement but as a local cache for relatively
static items available to JavaScript.
One practical use of web storage is to store static content downloaded asynchronously such as XML or
JSON from a web service in web storage, thus reducing server load for subsequent requests by the
session.
5.8 Caching
Every time a PHP page is requested, it must be fetched, parsed, and executed by the
PHP engine. For the typical PHP page, this might also involve numerous database
queries and processing to build.
If this page is being served thousands of times per second, the dynamic generation of that page may
become unsustainable.
One way to address this problem is to cache the generated markup in server memory so that subsequent
requests can be served from memory rather than from the execution of the page.
In this type of caching, the contents of the rendered PHP page (or just parts of it) are written to disk
for fast retrieval
There are two models for page caching: full page caching and partial page caching. In full page
caching, the entire contents of a page are cached. In partial page caching, only specific parts of a page
are cached while the other parts are dynamically generated in
the normal manner.
Application Data Caching
Many sites customize the content on each page for each user, so full or partial page caching may not
always be possible.
An alternate strategy is to use application data caching in which a page will programmatically place
commonly used collections of data into cache memory, and then other pages that also need that same
data can use the cache version rather than reretrieve it from its original location
While the default installation of PHP does not come with an application caching ability, a widely
available free PECL extension called memcache is widely used to provide this ability.
5.15 XML Processing
XML processing in PHP, JavaScript, and other modern development environments is divided into two basic styles:
The in-memory approach, which involves reading the entire XML file into memory into some type of data structure with
functions for accessing and manipulating the data.
The event or pull approach, which lets you pull in just a few elements or line at a time, thereby avoiding the memory load of
large XML files.