Databases Reference
In-Depth Information
and then modify the statements. This may sound silly, but several companies have
actually made such mistakes—and lost a lot of money as a result!
Validation, error checking, and security are large topics. Resources that discuss them
in more detail can be found in “Resources,” at the end of this chapter.
Sessions
The Web was designed for browsing documents, where each request from a web
browser to a web server was intended to be independent of each other interaction. To
develop applications for the Web, additional logic is required so that different requests
can be related. For example, code is required to allow a user to log in, use the applica-
tion, and log out when she's finished. In PHP, this logic is provided by the sessions
library. Sessions allow variables to be stored on the server, so that these variables can
be restored each time a user requests a script. Consider a short example:
<?php
// Initialize the session
session_start();
// If there is no "count" session variable, create one, and welcome
// the user.
if (!isset($_SESSION["count"]))
{
$_SESSION["count"] = 0;
echo "Welcome new user!";
}
// Otherwise, increment the number of visits and display a message.
else
{
$_SESSION["count"]++;
echo "Hello! You've visited this page {$_SESSION["count"]} times before.";
}
?>
The session_start function activates an existing session or, if none exists, creates a
new one. When the user requests the script for the first time, the $_SESSION["count"]
variable does not exist, so the isset( ) function returns the value FALSE . A new session
is created, and a new session variable count is defined in the $_SESSION superglobal
array, with its value set to 0. Session variables are stored on the web server; when the
user next requests the script, the isset( ) function returns TRUE , the $_SES
SION["count"] variable is automatically restored by the PHP engine, and the count in-
cremented. For example, on the fifth request of the script, the output is:
Hello!
You've visited this page 4 times before.
With its default configuration, the sessions library relies on cookies to maintain a
unique key. This key is used on the server to locate the variables associated with the
session. If cookies are disabled or unsupported by the browser, sessions won't work;
 
Search WWH ::




Custom Search