PHP5 II

 PHP5  Part II



PHP, HTML, and State
       Here we laern About PHP,HTML,and State. now you're familiar with HTTP, simple PHP programs, variables, and some of the PHP built-in functions, and although you can do a lot with what you've already learned, there's a key ingredient missing: user interaction! That's what this Post is all about, at least as far as Web-based applications are concerned.
      If you remember back before 1994 (a million years ago in Web time), early Web pages consisted of text, images, and links. The backgrounds were gray; there were no tables (much less DHTML and style sheets) to help structure pages; and there was little user interaction. The introduction of HTML elements for forms and form fields opened the door to direct, form-based interaction between the user and the Web server. HTML forms are today one of the most used (and most useful) means for interacting with online applications.

You'll explore HTML forms, but you'll also learn what kinds of data are available in HTTP requests and responses, and how you can use PHP to capture that data and then use it in your programs.

You'll examine the specifics of talking to the Web server (using the GET and POST methods), the format of requests and responses sent between client and server (and all the great data you can extract from them), and the nature of applications running across the Internet. You'll look at the concept of state, the lack of state in HTTP Web communications, and several methods for working around that deficiency. You'll get a look at PHP sessions as well.

HTML Primer
If you're an HTML wizard and have an in-depth understanding of the structure of HTML, you can probably skip this section, but for those of you who've never dissected HTML code or the HTML specification, read on. You'll recall that PHP's "middle name" is hypertext and that alone tells you that PHP is intertwined with HTML (Hypertext Markup Language). Understanding how HTML—particularly the HTML <form> element—works is very important to proficiency with PHP.

HTML was created by Tim Berners-Lee and Robert Caillau in 1989. It is a subset of Standard Generalized Markup Language (SGML). SGML was defined by International Standards in 1986 as ISO 8879:1986. SGML is designed to provide a common format for markup languages. HTML is called an SGML application because it is a language, whereas XML is simply a subset of the SGML specification used to make your own markup languages.
Like most SGML applications, HTML includes a Document Type Definition (DTD) that specifies the syntax of markup elements. You'll see examples of the HTML DTD throughout this primer.

The World Wide Web Consortium (W3C) can be found at www.w3.org. This organization maintains the HTML specification (now the XHTML specification). Visit the site and look for the HTML 4.01 specification to see all the elements and attributes.

HTML is a markup language, not a programming language. The primary purpose of HTML is to display data or content (such as text and images) along with hypertext links. HTML tags (the "commands" in HTML) help the Web page designer arrange the display of text, graphics, and multimedia. The only elements that give something resembling programmatic functionality are used to make tables, links, forms, and frames.

HTML is written in plain text, and when a page is requested all the code is sent in plain text format. Here's a simple HTML Web page (without a body):

<html>
<head>
<title>The Title</title>
</head>
</html>

                         Although the convention for many years was to write HTML tags uppercase (as in <HTML>), the HTML specification actually has no preference, and you can write conforming HTML tags either way, or even a mixture of upper and lower case (as in <hTmL>). However, the latest standard for HTML is now XHTML, which adheres to the XML specification, so there is a difference between uppercase and lowercase tags. XHTML specifies lowercase for tag names, which is why nearly every HTML tag in this book is lowercase. Browsers won't care whether the tags are uppercase or lowercase, but using lowercase will make it a lot easier to change your HTML to conform to XHTML.

An HTML Web page is made up of HTML tags, and most (but not all) of these tags have both beginning (opening) and ending (closing) tags. HTML tags are delimited by the angle brackets (<>). An HTML tag is named for the element it represents. For example, the tags <html> and </html> are the opening and closing tags for the HTML element. These tags signify the beginning and ending of the entire HTML document. Within these tags are the tags for the <head> of the document and for the title of the document. Tags contained within other tags are said to be nested.

Some HTML elements have only a beginning tag, such as the IMG element. When writing an IMG element (the IMG element inserts an external image file into a Web page) all you write is <img>, without en ending </img>. However, to tell the browser where to find the external image file, you place what is called an attribute in the beginning tag. HTML attributes are like fields in a database, or properties in an object, or variables in a program. They have names (such as SRC), and are containers for values. In fact, you set the value of the SRC attribute in the <img> tag to the URL of the image file name (like this: <img SRC="http://www.example.com/images/example.gif">). When the user's browser receives the HTML of the Web page, the browser reads the HTML, finds the URL of the image file, requests that file as well, and then inserts the file into the rendered Web page at the appropriate spot .
The HTML Document Type Definition
           A DTD declares what elements and attributes (and a few other things) that are allowed in an HTML document. Although an HTML document is made up of HTML tags, the HTML DTD uses a special format to specify what elements and attributes you can use. For example, because the HTML DTD specifies an IMG element, you can use the IMG element in a Web page.

But it's still up to the maker of your browser to properly recognize and display elements and attributes specified in the HTML DTD. In fact, deviations from the HTML specification are the primary reason a Web page may look (and work) fine in one browser and not in another.

Technically, HTML documents should start with a line indicating the DTD to be used, contained within the <!DOCTYPE> element. The DOCTYPE declaration indicates to the browser the proper DTD to use, but the inclusion of this line is not enforced by browsers. Many Web pages have no DOCTYPE declaration, but are still rendered correctly in browsers. Here's a DOCTYPE declaration inserted by Dreamweaver (a popular Web page design tool):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
The Form and Input Elements

One of the primary HTML elements you'll be working with is the <form> element. Take a look at how it's specified in the HTML DTD:

<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->
<!ATTLIST FORM
  %attrs;                                                                           -- %coreattrs, %i18n, %events --
  action                  %URI;                   #REQUIRED.         -- server-side form handler --
  method               (GET|POST)                 GET                 -- HTTP method used to submit the form --
  enctype               %ContentType;     "application/x-www-form-urlencoded"
  accept                 %ContentTypes;     #IMPLIED           -- list of MIME types for file upload --
  name                   CDATA                    #IMPLIED.          -- name of form for scripting --
  onsubmit             %Script;                 #IMPLIED           -- the form was submitted --
  onreset                %Script;                 #IMPLIED           -- the form was reset --
  accept-charset.    %Charsets;            #IMPLIED           -- list of supported charsets --
  >

The DTD for <form>begins with a line that names it as an element, and then specifies a list of attributes (ATTLIST). Notice the action attribute, which tells the browser where to send the contents of the form, and the method attribute, which tells the browser how to send the contents of the form.

The <input> element makes text fields, radio buttons, check boxes, and so on in a form. Here's its DTD:

The <input> element makes text fields, radio buttons, check boxes, and so on in a form. Here's its DTD:

<!ENTITY % InputType
  "(TEXT | PASSWORD | CHECKBOX |
    RADIO | SUBMIT | RESET |
    FILE | HIDDEN | IMAGE | BUTTON)"
   >
<!-- attribute name required for all but submit and reset -->
<!ELEMENT INPUT - o EMPTY                                             -- form control -->
<!ATTLIST INPUT
  %attrs;                                                                              -- %coreattrs, %i18n, %events --
  type                                   %InputType; TEXT                  -- what kind of widget is needed --
  name                                CDATA                     #IMPLIED -- submit as part of form --
  value                                CDATA                     #IMPLIED -- Specify for radio buttons and
checkboxes
--
  checked                            (checked)                 #IMPLIED -- for radio buttons and check boxes --
  disabled                           (disabled)                #IMPLIED -- unavailable in this context --
  readonly                           (readonly)               #IMPLIED -- for text and passwd --
  size                                   CDATA                     #IMPLIED -- specific to each type of field --
  maxlength                        NUMBER                 #IMPLIED -- max chars for text fields --
  src                                    %URI;                       #IMPLIED -- for fields with images --
  alt                                     CDATA                     #IMPLIED -- short description --
  usemap                            %URI;                      #IMPLIED -- use client-side image map --
  ismap                               (ismap)                    #IMPLIED -- use server-side image map --
  tabindex                          NUMBER                  #IMPLIED -- position in tabbing order --
  accesskey                        %Character;             #IMPLIED -- accessibility key character -
  onfocus                           %Script;                    #IMPLIED -- the element got the focus --
  onblur                             %Script;                    #IMPLIED -- the element lost the focus --
  onselect                          %Script;                    #IMPLIED -- some text was selected --
  onchange                        %Script;                    #IMPLIED -- the element value was changed --
  accept                             %ContentTypes;       #IMPLIED -- list of MIME types for file upload --
  >

The type attribute of the element specifies the type of control that will appear on the screen in your browser (text makes a text field, radio makes a radio button, and so on).

To create a Web page with a form in it, you could write the following HTML code in plain text, upload it to a Web server (or even just open it directly in your browser), and it would display as a nicely formatted Web page:

<html>
<head>
<title>
</title>
</head>
<body bgcolor="white">
<form method="post" action="http://www.example.com">
Username:<input type="text" name="username"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

This code creates a simple form with two fields (username and password) and a submit button. When submitted, the form's contents are sent to www.example.com.

How can you make HTML forms and PHP work together to make Web pages that are dynamically generated (rather than simply copied to your browser by the Web server)? First, you create a Web page using plain text HTML tags, and include an HTML form within that page. Then, you write PHP code within the Web page, making sure the code is properly enclosed by the <?php and ?> delimiters.

When the Web page is requested by a browser, any PHP code in it is resolved or processed by the PHP scripting engine before the results are returned to the user, and the results of PHP processing are placed in exactly the same spot as the original PHP code. You also could write your code so that it is only processed when there is a form submission (you'll see how in the next few sections). It may even use some of the submitted form data in its processing.

The end result of the PHP processing is HTML compatible, but because the PHP scripting engine has a chance to perform some processing before the final version of the Web page is sent, some of the content of the page (any parts generated by the PHP code) may differ each time the page is requested. And if processing takes place in response to a form submission, there are a great variety of interactive features that can be created.
Accessing PHP and HTTP Data

You know how HTTP works and you basically understand clients and servers, so you're very cognizant of the interaction between your browser (a client application) and the Web server (a server application) when running PHP programs online. In this Post you explore HTML forms and examine how they facilitate user interactions with the Web server (and thereby your PHP programs). These topics deserve a lot of attention because HTTP, HTML, and PHP are tightly intertwined. A good understanding of what's going on between the browser and the server is essential for PHP programming because within the requests and responses flying back and forth from client to server is a wealth of data you can utilize.
Each time you click a link or submit a form, you send a great deal of data about your system and your browser to the Web server, and each time the Web server responds, it sends you a great deal of data about itself. PHP has the capability to capture the data that is submitted by a browser, and also provides a means of getting at data about PHP's installation on the server. For instance, if you go to your favorite PHP-driven Web site and log in, it's likely that a predefined variable named $_POST is filled (on the server) with your username and password, another predefined variable named $_SERVER contains information about the current Web server environment, and that both are available to the PHP application running the site. These aspects of PHP are discussed in depth in the next few sections, but it's really kind of surprising how much data is available (especially considering that most folks aren't even aware of it). Read on to learn how to access all this data.

Predefined Variables
PHP automatically makes quite a few variables (called predefined variables) available anywhere in your program. They are array variables, and you can access them by name, like any other variable. By default, PHP is configured not to populate these variables (in the php.ini file, the default register_globals=Off is in place), you must use their entire name to access their data. For example, if a form has a text field named username and this field is filled out and submitted (and assuming the form's submission method is POST), you can access the field's data by code such as this:

$my_new_username = $_POST[username];

Predefined variables are also called superglobal variables because they can be accessed without regard to scope. Predefined variables consist of most of the information contained in HTTP requests and responses, including server variables, query strings, form variables, and so on. You can use predefined variables for any purpose, just like ordinary variables, but some of them may or may not be present for any given installation of PHP because Web servers vary in the data provided via HTTP. In the next section you'll see how to retrieve the data in predefined variables.

In addition to predefined variables, you can use the built-in PHP function phpinfo() to get basic PHP installation and operating information. This function not only enables you to test whether PHP is installed and working  but also enables you to find out many details about how PHP is installed on the server. For example, you can find out what version of PHP is running, what OS your server is running on, and so forth.

Perhaps an easier way to demonstrate what you get from the phpinfo() function is simply to run the test01.php file created in again. This time you're running it not just to see if the installation of PHP worked but to examine the various kinds of data it provides. When run from your Web server, phpinfo() creates a very nicely formatted and detailed page (including all the required HTML tags) describing the PHP version, operating system, version of the ZEND engine, settings in your php.ini file, additional modules, and predefined variables .
Variables in HTTP Request and Response
There's a surprising amount of data passed back and forth between the client and the Web server (and vice versa). For example, not only is the IP address of the client passed to the Web server with each request (not actually very surprising, as how else would the Web server know where to send the response) but also details about what version of browser is making the request, cookies, form data, Web server version, and so on. The data is contained in predefined variables structured as associative arrays, so that you can access them by name, just like you would access any other array. The contents of each and what you might want to use them for are presented after the following "Try It Out."

There is a setting in your configuration file (php.ini) called register_globals. The default is off (since PHP4.2), and it restricts how you can access some predefined variables. From a practical standpoint, this means you should use the full name of the array ($_SERVER['DOCUMENT-ROOT'] is the example given) to access data in predefined variables. There is the function (import_request_variables()) that will import GET, POST, and Cookie variables into the global scope, so you can access them directly by name, but the full array name is recommended and therefore used in this post.

Links
If you've ever done any Web page design or programming, you're undoubtedly familiar with the structure of a link in HTML. In technical terms, an HTML link uses the anchor element (whose starting and ending tags are <a> and </a>), and one of its main attributes, href, which has a URL as its value. Text or images placed inside the beginning and ending <a> tags make a link that, when clicked, goes to the URL in the href attribute, like this:

<a href="http://www.myplace.com">Click Here</a>


So clicking a link is one form of user interaction enabling you to communicate with the server. But it's pretty limited, because all you can do is make a request for the page that's already supplied by the site designer. For example, if I click a link to the About page, the only reason it goes to the right page is because the site designer has already hard-coded the link with the URL for that page.

Query Strings

Somewhat more flexible is the query string, which is attached to the end of the URL in a link. A query string can consist of as many name/value pairs as you (the developer) want to supply. The big difference is that PHP provides a means by which the user can supply values that can be embedded in the query string. Say, for example, that the user has entered a value of John as his first name, and your PHP program can make use of that value via its variable name ($first_name, for instance).

The term name/value pair is a generic way of referring to any situation in which you have a named container for a value. Name/value pairs include fields in a table in a database, variables, HTML and XML attributes, and so on.

You could write a PHP program that generates a query string attached to a URL using code such as this (assuming you had the $first_name and $last_name variables already set):

<a href="http://www.myplace.com?first_name=<?php echo $first_name; ?>">Click
Here</a>

When this code runs, it produces the following output:

<a href="http://www.myplace.com?first_name=John">Click Here</a>

Notice how a query string is constructed: a question mark followed by the name of the first name/value pair, an equals sign, and the value in the first name/value pair. If you had both a first name and a last name, you could have included both name/value pairs in the query string by connecting them with an ampersand (&), like so:

<a href="http://www.myplace.com?first_name=<?php echo $first_name;
?>&last_name=<?php echo $last_name; ?>">Click Here</a>

Putting both name/value pairs in the query string would result in the following (if you're a dead movie star):

<a href="http://www.myplace.com?first_name=John&last_name=Wayne">Click
Here</a>

Query strings are often useful (especially in preserving values between page requests, which are discussed that a bit more later in the post, but as you can see they are still quite limited. For one thing, to place a user-supplied value in a query string, you have to already have it. You could get it from a database, but if you needed to get it from the user before using it, you'd have to provide the user with some free form method of supplying it. And that brings us to a very powerful method for user interaction, the HTML form.

The Concept of State
You're familiar with how desktop applications such as Excel, Word, Dreamweaver, and so on work. You start them up, they appear on your screen, and you do your work via documents, menu choices, dialog boxes, controls, and form fields. It can easily appear that there is no separation between the application's data processing logic and the user interface, but in fact every time you choose something from a menu, click a button, or enter something in a form field, you are actually using the user interface, and the user interface is communicating what you just did to the programming logic inside the application. The application then responds by performing its processing and providing a response to the user interface. For some actions you take there may be no visible response, whereas for others it is plain that a great deal of processing has taken place behind the scenes.

The point of this discussion is that as you provide input to the application via the user interface, you change the overall state of the application. You can think of state as the exact condition, moment to moment, of all the data and variables in the application. And the application has an obligation to take note of state changes, because it might have to respond to these changes with an action of its own (which then further changes the state of the application).

There are many things besides user interaction that can change the state of an application. For example, suppose you're playing a game and you have 15 seconds to make your move. The application will monitor the system clock and may make an action entirely independent of anything you do (except make your move) based on how many seconds have elapsed (another case of state change). What does this have to do with you? Well....

As a programmer, you may not think much about state when programming desktop applications, because you're used to seamless communications between your user interface and your programming logic. But programming for the Web forces you to address the issue, because HTTP communications are stateless. HTTP is a stateless protocol because there is no built-in mechanism that tracks the state of every object in the user interface and informs the programming logic of it, or vice versa.

Instead, communications between browser and server take the form of clicks on links or form submissions. Not only is this driven by the user (instead of being automatic), but for folks with slower connections or intermittent connections it can be slow and time-consuming. So building an online application with PHP requires you to use other mechanisms for maintaining state, and you need to take measures to cope with the fact that the user interface is disconnected and may not respond at all in the way you would ordinarily expect.

State Maintenance

The most direct way in which you'll be involved with state in PHP programs is when trying to preserve variable values between page requests because each page is its own program, and once the program is done processing, all variables and values are lost—the program's done, and everything is erased out of memory. Unlike desktop applications, which maintain data in memory until you shut them down, a PHP program runs only when a page request activates it, and then only until processing is completed and/or HTML or text content is returned to the user.

PHP is able to bridge the gap between each request-response and the next, providing persistence of data—and, yes, prolonged interactivity. This process of continually updating the server with information, a major ingredient in most interactive sites, is necessary to maintain a session. Session maintenance is how you refer to a series of interactions, beginning with the user accessing or logging on to a site, and ending with the user logging out or being timed out for inactivity.

The key to this process is usually a cookie (a small piece of data stored on the client's computer) or some sort of a variable that the client and server pass back and forth, often called a session key. These cookies and keys are used to help the server know which client it is interacting with for any given request. Just as a username identifies a user to a system, a session key (or an appropriate cookie) identifies a client to a Web site.

Sessions also maintain state across page requests and you'll examine them in detail a little later. First, take a look at some other methods available to you, including the use of hidden form fields, query strings, databases, and cookies.
Hidden Form Fields

You've seen how hidden form fields work to send data (coded by the designer) back to the server when the form is submitted. If you want to maintain state using hidden form fields (for example, a unique value representing a product the user is working with, such as the product ID), you can simply place the current product ID value into a hidden form field. Of course, the idea is that you would have the user select the product from a drop-down box (the select element) and then submit the form, using something like this code:

<form action="myform.php" method="post"> Query strings can be used in exactly the same way as hidden form fields to maintain state values across page requests. However, as previously discussed, their name/value pairs are displayed for all to see in the address bar of the browser, along with the URL. This is a very insecure method of transmitting data, and as you've probably guessed, easy for malicious users to break, disable, or otherwise mess with.


<select name="selected_product_id">
<option value="121">Product 121</option>
<option value="122">Product 122</option>
</select>
<input type="submit" name="button" value="Select Product">
</form>

You could return a page to him using the following code:

<input type="hidden" name="chosen_product_id" value="<?php echo
$selected_product_id; ?>">

Before the page is returned, the user's input would be processed as follows (assuming he chose product 122):

<form action="myform.php" method="post">
<input type="hidden" name="chosen_product_id" value="122">

So the next time he submits this form, part of the data submitted would be chosen_product_id, which PHP would turn into $chosen_product_id, and which you could then use anytime you wanted to perform processing on the product he chose, no matter how many page requests ago he chose that product. Don't forget, though, you'll need to populate that same hidden form field value each time the user requests another page or you'll lose that value.
Query Strings

Query strings can be used in exactly the same way as hidden form fields to maintain state values across page requests. However, as previously discussed, their name/value pairs are displayed for all to see in the address bar of the browser, along with the URL. This is a very insecure method of transmitting data, and as you've probably guessed, easy for malicious users to break, disable, or otherwise mess with.
Databases
The mechanics of databases and database access haven't been discussed yet  but you're certainly aware that databases are useful for storing structured information persistently (meaning that the data is retained even if the server is turned off), so you can understand why databases are useful for storing data across page requests. Basically, if you don't mind the extra overhead of making a query on the database each time a page request occurs, you can use a table in the database to store all pertinent data that must be preserved across page requests. The downside, of course, is the overhead involved in those database connections, and the extra effort building the database in the first place.

Cookies
So what are cookies? They're a quick (and some would say messy) method of storing, on the client's computer, small snippets of data that you want to persist between separate visits to a Web site. They aren't very powerful or reliable—you certainly wouldn't want to use them for permanent data storage, because the mere act of switching browsers completely obliterates all your old cookies. But they can be very handy for a wide variety of things. Some of the most common examples of cookie use include the following:

1. Storing a user's aesthetic preferences for a specific site.

2. Storing a user key (or keys) that can be used to link users with their personal data—as used in countless shopping basket features, for example.

3. Providing a semi-permanent session key, enabling a user to remain logged on to a site until he explicitly asks to leave it or the browser closes.

Cookies are best used for small, helpful but non-critical things. One of the best examples of cookie use is to store preferences describing how a user wants your site to appear. Although the capability to customize a site's color scheme is a nice perk for users, those who can't (or won't) use cookies won't be missing much.

Intended as innocuous "helpers" for Web developers, cookies have built up a bad reputation in recent years. They are often overused (for example, to store large quantities of data which is really best kept on the server end) and sometimes even abused (to gather information on consumers without their knowledge, for instance). If used sparingly and responsibly, though, cookies can be useful in a number of situations. They tend to be most useful:

1. In situations where you know for a fact that all the visitors to your site will have cookie support enabled—on corporate and educational intranets, for example.

2. To add bells and whistles to a site—features that add to a site's appeal but aren't required to make use of it.

Messing Around with Cookies

Exact details of how cookies are implemented vary from browser to browser, but certain important points apply across the board, and these are as follows:

1. A cookie is a short piece of data that can be used to store a variable's name and value, along with information on the site from which it came and an expiry time.
2. Cookies provide client-side storage, usually held in files on the client machine's hard drive.

3. Web sites can usually only modify their own cookies.

4. They can be accessed and (if the appropriate security criteria are met) altered at will by the Web server from which they were originally sent.

When a client accesses a Web site that uses cookies, the Web server tells the client (usually a Web browser) to store away a given piece of data for later use. The client is then responsible for storing that data away. Cookie-supporting browsers accomplish this by storing the data in a file named after the site the cookie belongs to, in a directory they keep reserved for this purpose. On subsequent requests to that site, the client sends back a copy of that data—the data persists on the client side until a specified period expires, causing it to be removed from the system. This specified period is set by the server when it tells the client to create the cookie, and is basically a number of seconds for which the client should keep the cookie. If the server tells the client to set an expiry period of zero seconds, the browser should keep the cookie only until the user quits the browser application.

Because cookies are kept on the client side, they're not under the control of the server once they've been created. Users can elect to delete cookies themselves, often simply by clicking a button in their browser, or by deleting the browser's cookie files. They could also edit the contents of the files if the urge took them. Just because you wrote what's in the cookie, doesn't mean you should always expect the right data to come back!

Essentially, cookies are the server telling the client "here's something to remember; remind me of it when you come back next time." Next time could be anything from when you click that link two seconds from now to when you come back next week. That's some serious persistence! It's a little like being at a conference where delegates can be identified by their name badges for as long as they care to wear them.

Web servers send clients cookies in HTTP headers, which are sent before any HTML text. Likewise, clients send back those cookies using HTTP headers. A client knows which cookies to share with a Web site, based on the server and path the client is currently accessing. So, if you're accessing www.php.net, the browser doesn't send any cookies it received from www.wrox.com.

When a cookie is set, a server name and path name can optionally be set—this limits access to the cookie to the specified server and/or path on that server. Clients use this information to determine whether they should send any given cookie. A cookie-enabled browser generally sends any and all cookies that it thinks applicable to a given site in the headers of any given access.

Set and Retrieve Cookies
PHP, as a modern Web scripting language, comes with full support, and setting cookie variables is as simple as making a call to setcookie(). As with header(), setcookie() must be called before any HTML is printed to the client's browser because cookies are set in the HTTP headers, which must be sent before any HTML.

The setcookie() function takes six parameters, of which the first three are by far the most important: These are, in order:

1.  A string to be used as the name of the variable.

2.  A string to be used as the value of the variable.

3.  A UNIX timestamp denoting the time at which the cookie will expire.

A UNIX timestamp is simply a long integer that represents a time and date by counting seconds since midnight on 01/01/1970. You can get the current time in this form by using the function time(). If you want to set a cookie to expire an hour from now, simply specify time() + 3600 for the third parameter.

The last three parameters to setcookie() are less frequently used:

1.  The path to whose files the cookie is relevant; the browser doesn't return cookies that are from inappropriate paths. For example, if you set this parameter to /my/path/number/one and accessed a page in /my/path/number/two, your browser wouldn't send the cookie. If you went back to a page in /my/path/number/one, the browser would send the cookie.

2.  The domain to which the cookie applies; same rules apply as to the preceding parameter. This parameter may be useful if your Web server hosts multiple domains.

3.  An integer called secure. Set it to 1 if you only want your cookie to be sent when requesting an SSL-encrypted page. (The cookie won't be stored in an encrypted form on the client's hard drive; this setting merely ensures that the cookie will be encrypted for transmission across the Internet.)

In the simplest possible situation, you could leave off these last three, so that a typical call to setcookie() might look like this:

setcookie("fontprefs", "", time()+3600);

Accessing cookies is even simpler—there's nothing to call at all! Just as it does with POST variables, PHP automatically puts cookie information in the global domain, so it's as simple to use cookie values as it is to use any other variables. For example, the value of a received cookie called fontprefs is automatically be available throughout the script as the global variable
$_COOKIES['fontprefs'].

There are several ways to delete a cookie. Of course, if the client knows where to look on his machine, he can always edit or delete the files in which cookies are stored. However, it's sometimes useful to be able to get the server to delete (or "eat") a cookie, and if this is the case, there are two main options:

1. Reset the cookie's expiry time to a time in the past: setcookie("num", "0", time() -9999);, for example.

2. Reset the cookie, specifying only its name: setcookie("fontprefs");, for example.
The last three parameters to setcookie() are less frequently used:

The path to whose files the cookie is relevant; the browser doesn't return cookies that are from inappropriate paths. For example, if you set this parameter to /my/path/number/one and accessed a page in /my/path/number/two, your browser wouldn't send the cookie. If you went back to a page in /my/path/number/one, the browser would send the cookie.

The domain to which the cookie applies; same rules apply as to the preceding parameter. This parameter may be useful if your Web server hosts multiple domains.

An integer called secure. Set it to 1 if you only want your cookie to be sent when requesting an SSL-encrypted page. (The cookie won't be stored in an encrypted form on the client's hard drive; this setting merely ensures that the cookie will be encrypted for transmission across the Internet.)

In the simplest possible situation, you could leave off these last three, so that a typical call to setcookie() might look like this:

setcookie("fontprefs", "", time()+3600);

Accessing cookies is even simpler—there's nothing to call at all! Just as it does with POST variables, PHP automatically puts cookie information in the global domain, so it's as simple to use cookie values as it is to use any other variables. For example, the value of a received cookie called fontprefs is automatically be available throughout the script as the global variable $_COOKIES['fontprefs'].

There are several ways to delete a cookie. Of course, if the client knows where to look on his machine, he can always edit or delete the files in which cookies are stored. However, it's sometimes useful to be able to get the server to delete (or "eat") a cookie, and if this is the case, there are two main options:

Reset the cookie's expiry time to a time in the past: setcookie("num", "0", time() -9999);, for example.

Reset the cookie, specifying only its name: setcookie("fontprefs");, for example.

Native Sessions in PHP

A session can be defined as a series of related interactions between a single client and the Web server, which take place over an extended period of time. This could be a series of transactions that a user makes while updating his stock portfolio, or the set of requests that are made to check an e-mail account through a browser-based e-mail service. The session may consist of multiple requests to the same script, or of requests to a variety of different resources on the same Web site.

Particularly when you want to work with sensitive (or bulky) information, it makes a lot of sense to submit it once and have it stored on the server. Rather than storing the actual data on the client machine, and have to pass it back and forth between the server and client each time, it's far more practical to keep the data on the server, but give the client a "key" to allow it to uniquely identify itself, and consequently any server-side data associated with it. This key is called a session identifier; it uniquely associates a client with a session, and therefore with its data. In PHP, the session identifier is known as the SID (Session ID). SID is a special variable that's specified as a reference number for any particular session.

You saw how to establish a session of sorts when you used cookies to make data persist on the client machine. As noted at the time, though, that isn't a terribly secure way to manage sessions. Fortunately, PHP comes with its own session management system built in, so you don't need to worry too much about the precise implementation details. PHP creates its SID whenever you use the session_start() function, and also by default if you use certain other session-related functions, such as session_register(). The value of the SID is kept in a global variable named PHPSESSID.

You can think of the SID as being like the reference number on an electric bill: you're given the number, the electric company files your details under that number, and presto! You no longer have to give the company all your details every time you call up to complain about its outrageous charges. The SID is automatically created and passed back and forth for you, each time the user clicks a link or submits form.

When you start a PHP session, the server assigns it a session ID, or SID. Any variables that you register as session variables (you'll see how to do this in a moment) are then stored on the server in a cookie-like file. The name of this file is generally the same as the value of the SID. All the client has to do to access this data is to include the SID in its request to the server. It can use a hidden form field, a query string, a cookie, anything at all, as long as the SID makes it into the HTTP request. The server looks up the appropriate session data and makes it available for use in whatever script it then executes.

If you have cookie support enabled, even this is taken care of, because the session manager automatically sends the client a cookie for the SID value. If you can't (or don't want to) use cookies, the simplest thing to do is to add the SID as a term in all query strings that point back to your Web site.

PHP sessions handle this all very neatly; they're an excellent way to learn how to build interactive sites quickly because they completely free you up from worrying about the nitty-gritty details of implementing persistence, and let you get on with the business of building your site. One particularly nice aspect is the knowledge that you have literally thousands of coders scrutinizing your persistence mechanism (because it's a part of PHP itself!) and ensuring that the underlying code works as well as possible. What's more, sessions are very well documented in the core PHP documentation, available at the official PHP Web site (www.php.net/). So, sessions are easy, reliable, and almost universally available; but how exactly do you use them?

In most cases, using PHP sessions is as simple as telling PHP, "I want variables X, Y, and Z to remain persistent," and letting PHP do the work. All that you, the coder, need to worry about is how to tell PHP to register a session variable—that is, make a given variable persistent—and then how to access those variables.

The function for registering a persistent variable for use with PHP sessions is session_register(). Given the name (without the dollar sign) of a variable, it makes that variable and its contents persist for the duration of the current session. If there isn't currently a session defined, a new one is created automatically. The length of the session (how long the session remains intact without the user having to use the site) is determined by the session timeout setting in the php.ini file. The default is 1,440 seconds (24 minutes).

If you wanted to maintain persistent variables called myvar1 and myvar2, for example, here's how you'd begin your PHP script:

<?php
session-register("myvar1");
session-register("myvar2");
?>

You must put this code at the top of the script. Behind the scenes, you're using cookies. Again, to not mess with HTTP headers, you must be sure to register all the session variables before any HTML headers are sent out. It's good practice to do so at the very top of a script, in a self-contained snippet of PHP, as shown.

Once you've registered a variable, retrieving its contents is ridiculously simple—just access the session variable as if it were any other global variable! If you used the preceding code to register variables $myvar1 and $myvar2, you can use them just like any other variables. The only difference is that they persist for as long as the session lasts, so that the next time the page is called within the session, by the same user, the variables will contain the same values they had when the page finished executing the last time.

To use PHP sessions with Windows, you may need to modify the variable session.save_path in your php.ini file so that it refers to a valid Windows directory (D:\WinNT\Temp, for example, where D is the letter for your hard drive).

Summary

This Post covered the many predefined variables available to your PHP program anytime a request and response occurs between the client and the Web server. The display and use of individual predefined variables such as $_SERVER, $_REQUEST, and so on also were discussed.

You learned the basics for making your PHP programs interactive: query strings in links (using the <a> element) and HTML forms (using the <input>, <textarea>, and <select> elements). You also learned the differences between the GET and POST methods, and examined the circumstances under which you might want to use one over the other.

Finally, you explored the concept of state, what it means that HTTP is stateless, and how to overcome HTTP's stateless limitations using hidden form fields, query strings, cookies, sessions, and even databases to store and transmit state information across page requests.
Thank you.I hope this post help you.









Post a Comment

Previous Post Next Post