Tuesday, August 11, 2009

Moving Information from One Web Page to the Next

ost Web sites consist of more than one Web page. This includes the static Web pages that you may have developed in the past. With static
Web pages, users click links to move from one page to the next. Users click a link in one Web page, and a new Web page appears in their browser. When users move from page to page this way, no information is transferred from the first page to the second. Each new page that is sent to the user’s browser is independent of any other pages that the user may have seen previously. With dynamic Web pages, you may need to transfer information from one page to the next. If you are an advanced HTML developer, you may have some experi­ ence with limited methods for transferring information from one page to the next by using HTML forms and CGI (Common Gateway Interface) or cookies. However, PHP is much more powerful for passing information from Web page to Web page.

Moving Your User from
One Page to Another

When using HTML only, you provide links so that a visitor can go from one page to another in your Web site. When using PHP, however, you have three options for moving your user from one page to the next.

Links: You can echo the HTML tags that display a link. The general
format of an HTML statement that displays a link is

<a href=”newpage.php”>Text user sees as a link</a>

When users click the link, the program newpage.php is sent to their browser. This method is used extensively in HTML Web pages. You’re likely familiar with creating links from your HTML experience, but if you need a refresher, find out more about links in any HTML book, such as HTML 4 For Dummies Quick Reference, 2nd Edition, by Deborah S. Ray and Eric J. Ray ( Wiley).

Form submit buttons: You can use an HTML form with one or more submit buttons. When the user clicks a submit button, the program in the form tag runs and sends a new Web page to the user’s browser. You can create a form with no fields — only a submit button — but the user must click the submit button to move to the next page.

I discuss forms and submit buttons thoroughly in Chapter 8.

The header function: You can send a message to the Web server that tells it to send a new page by using the PHP header function. When using this method, you can display a new page in the user’s browser without the user having to click a link or a button.

The PHP header function can be used to send a new page to the user’s browser. The program uses a header statement and displays the new Web page without needing any user action. When the header statement is exe­ cuted, the new page is displayed. The format of the header function that requests a new page is

header(“Location: URL”);

The file located at URL is sent to the user’s browser. Either of the following statements are valid header statements:

header(“Location: newpage.php”);
header(“Location: http://company.com/catalog/catalog.php”);

The header function has a major limitation, however. The header statement can only be used before any other output is sent. You cannot send a message requesting a new page in the middle of a program after you have echoed
some output to the Web page. See the sidebar for a discussion of “Statements that must come before output.”

URLs

A URL (Uniform Resource Locator) is an address on the World Wide Web. Every Web page has

site is ready for customers, it is made avail­
able on port 80.

its own URL or address. The URL is used by the Web server to find the Web page and send it to a browser.

The format of a URL is

HTTP://servername:portnumber/
path#target?string=string

Here’s a breakdown of the parts that make up the URL:

HTTP://servername: This tells the server that the address is a Web site and gives the name of the computer where the Web site is located. Other types of transfer can be specified, such as FTP (File Transfer Protocol), but these aren’t related to the subject of this book. If this part of the URL is left out, the Web server assumes that the computer is the same computer that the URL is typed on. Valid choices for this part are HTTP://amazon.com or HTTP:// localhost. Note: HTTP doesn’t have to be in uppercase letters.

path: This is the path to the file, which fol­ lows the rules of any path. The root of the path is the main Web site directory. If the path points to a directory, rather than a file, the Web server searches for a default file name, such as default.html or index. html. The person who administers the Web site sets the default file name. The path /catalog/show.php indicates a directory called catalog that is in the main Web site directory and a file named show.php. The path catalog/show. php indicates a directory called catalog that is in the current directory.

#target: An HTML tag defines a target.
This part of the URL displays a Web page at the location where the target tag is located. For instance, if the tag <a name=
”target”></a> is in the middle of the file somewhere, the Web page will be dis­ played at the tag rather than at the top of the file.

:portnumber: The

Web

server

?string=string: The question mark

exchanges information with the Internet at
a particular port on the computer. Most of the time, the Web server is set up to com­ municate via port 80. If the port number isn’t specified, port 80 is assumed. In some unusual circumstances, a Web server may use a different port number, in which case the port number must be specified. The most common reason for using a different port number is to set up a test Web site on another port that’s available only to devel­ opers and testers, not customers. When the

allows information to be attached to the end of the URL. The information in forms that use the get method is passed at the end of the URL in the format fieldname=value. You can add information to the end of a URL to pass it to another page. PHP automati­ cally gets information from the URL and puts it into built-in arrays. You can pass more than one string=string pair by sepa­ rating each pair with an ampersand (&): for example, ?state=CA&city=home.

Statements that must come before output

Some PHP statements can only be used before sending any output. header statements, setcookie statements, and session functions, all described in this chapter, must all come before any output is sent. If you use one of these statements after sending output, you may see the following message:
Cannot add header information - headers already sent

The message will also provide the name of the file and indicate which line sent the previous output. Or you might not see a message at all; the new page might just not appear. (Whether you see an error message depends on what error message level is set in PHP; see Chapter 6 for details.) The following statements will fail because the header message is not the first output:
<html>
<head><title>testing header</title></head>
<body>
<?php
header(“Location: http://company.com”);
?>
</body>
</html>

Three lines of HTML code are sent before the header statement. The following statements will work, although they don’t make much sense:
<?php
header(“Location: http://company.com”);
?>
<html>
<head><title>testing header</title></head>
<body>
</body>
</html>

The following statements will fail:

<?php
header(“Location: http://company.com”);
?>
<html>
<head><title>testing header</title></head>
<body>
</body>
</html>

The reason why these statements fail is not easy to see, but if you look closely, you’ll notice a single blank space before the opening PHP tag. This blank space is output to the browser, although the resulting Web page looks empty. Therefore, the header statement fails because there is output before it. This is a common mistake and difficult to spot.

In spite of its limitation, the header function can be useful. You can have as many PHP statements as you want before the header function as long as they don’t send output. Therefore, the following statements will work:

<?php
if ($customer_age < 13)
{
header(“Location: ToyCatalog.php”);
}
else
{
header(“Location: ElectronicsCatalog.php”);
}
?>

These statements run a program that displays a toy catalog if the customer’s age is less than 13 but run a program that displays an electronics catalog if the customer’s age is 13 or older.

Moving Information from Page to Page

HTML pages are independent from one another. When a user clicks a link, the Web server sends a new page to the user’s browser, but the Web server doesn’t know anything about the previous page. For static HTML pages, this process works fine. However, many dynamic applications need information to pass
from page to page. For instance, you might want to store a user’s name and refer to that person by name on another Web page.

Dynamic Web applications often consist of many pages and expect the user to view several different pages. The period beginning when a user views the first page and ending when a user leaves the Web site is a session. Often you want information to be available for a complete session. The following are examples of sessions that necessitate sharing information among pages:

Restricting access to a Web site: Suppose that your Web site is restricted and users log in with a password to access the site. You don’t want users to have to log in on every page. You just want them to log in once and then be able to see all the pages that they want. You want users to bring information with them to each page showing that they have logged in and are authorized to view the page. You want users to log in and remain logged in for the whole session.

Providing Web pages based on browser: Because browsers interpret some HTML features differently, you might want to provide different ver­ sions of your Web pages for different browsers. You want to check the user’s browser when the user views the first page and then deliver all
the other pages based on the user’s browser type and version.

With PHP, you can move information from page to page by using any of the following methods:

Adding information to the URL: You can add certain information to the end of the URL of the new page, and PHP will put the information into built-in arrays that you can use in the new page. This method is most appropriate when you need to pass only a small amount of information.

Storing information via cookies: You can store cookies — small amounts of information containing variable=value pairs — on the user’s computer. After the cookie is stored, you can get it from any Web page. However, users can refuse to accept cookies. Therefore, this method only works in environments where you know for sure that the user will have cookies turned on.

Passing information using HTML forms: You can pass information to a specific program by using a form tag. When the user clicks the submit button, the information in the form is sent to the next program. This method is very useful when you need to collect information from users.

Using PHP session functions: Beginning with PHP 4, PHP functions are available that set up a user session and store session information on the server; this information can be accessed from any Web page. This method is very useful for sessions in which you expect users to view many pages.

Adding information to the URL

A simple way to move information from one page to the next is to add the information to the URL. Put the information in the following format:

variable=value

The variable is a variable name, but do not use a dollar sign ($) in it. The value is the value to be stored in the variable. You can add the variable=value pairs anywhere that you use a URL. You signal the start of the information with a question mark (?). The following statements are all valid ways of passing information in the URL:

<form action=”nextpage.php?state=CA” method=”POST”>

<a href=”nextpage.php?state=CA”>go to next page</a>

header(“Location: nextpage.php?state=CA”);

You can add several variable=value pairs, separating them with ampersands
(&) as follows:

<form action=”nextpage.php?state=CA&city=home” method=”POST”>

Here are two reasons why you might not want to pass information in the URL:

Security: The URL is shown in the address line of the browser, which means that the information that you attach to the URL is also shown. If the information needs to be secure, you don’t want it shown so publicly. For example, if you’re moving a password from one page to the next, you probably don’t want to pass it in the URL. Also, the URL can be book­ marked by the user. There may be reasons why you don’t want your users to save the information that you add to the URL.

Length of string: There is a limit on the length of the URL. The limit dif­ fers for various browsers and browser versions, but there is always a limit. Therefore, if you’re passing a lot of information, there may not be room for it in the URL.

Adding information to the URL is very useful for quick, simple data transfer. For instance, suppose that you want to provide a Web page where users can update their phone numbers. You want the form to behave in the following way:

1. When the user first displays the form, the phone number from the data­ base is shown in the form so that the user can see what number is cur­ rently stored in the database.

2. When the user submits the form, the program checks the phone number to see whether the field is blank or whether the field is in a format that could not possibly be a phone number.

3. If the phone number checks out okay, the number is stored in the
database.

4. If the phone number is blank or has bad data, the program redisplays the form. However, this time you don’t want to show the data from the database. Instead, you want to show the bad data that the user typed and submitted in the form field.

The displayPhone.php program in Listing 9-1 shows how to use the URL
to determine whether this is the first showing of the form or a later showing. The program shows the phone number for the user’s login name and allows the user to change the phone number.

Notice the following key points about this program:

The same program displays and processes the form. The name of this program is displayPhone.php. Notice that the form tag includes action=displayPhone.php, meaning that when the user clicks the submit button, the same program runs again.

Information is added to the URL. The form tag includes action=displayPhone.php?first=no. When the user clicks the submit button and displayPhone.php runs the second time, a variable $first is passed with the value “no”.

The value that was passed for first in the built-in $_GET array is checked at the beginning of the program. This is to see whether this is the first time that the program has run.

If $_GET[first] equals “no”, the phone number is checked.
$_GET[first] only equals no if the form is being submitted.
$_GET[first] does not equal no if this is the first time through the program.

• If the phone number is okay, it is stored in the database, and the program ends.

• If the phone number is not okay, an error message is printed.

If $_GET[first] does not equal “no”, the phone number is retrieved from the database. In other words, if $_GET[first] doesn’t equal no, it is the first time that the program has run. The program should get the phone number from the database.

If the program reaches the statements that display the form, the form is displayed. If this is not the first time through the program and a
phone number was submitted and was okay, the phone number is stored in the database, and the program stops. It never reaches the statements that display the form. In all other cases, the form is displayed.

The form displayed by the program in Listing 9-1 is shown in Figure 9-1. This shows what the Web page looks like the first time that it’s displayed. Notice that the URL in the browser address field doesn’t have any added information.

Figure 9-2 shows the results when a user types a nonsense phone number in the form in Figure 9-1. Notice that the URL in the browser address field now has ?first=no added to the end of it.

Storing information via cookies

You can store information as cookies. Cookies are small amounts of information containing variable=value pairs, similar to the pairs that you can add to a URL. The user’s browser stores cookies on the user’s computer. Your applica­ tion can then get the cookie from any Web page. Why these are called cookies
is one of life’s great mysteries. Perhaps they’re called cookies because they seem at first glance to be a wonderful thing, but on closer examination, you realize that they aren’t that good for you. For some people in some situations, cookies are not helpful at all.

At first glance, cookies seem to solve the entire problem of moving data from page to page. Just stash a cookie on the user’s computer and get it whenever you need it. In fact, the cookie can be stored so that it remains there after the user leaves your site and will still be available when the user enters your Web site again a month later. Problem solved! Well, not exactly. Cookies are not under your control: They’re under the user’s control. The user can at any time delete the cookie. In fact, users can set their browsers to refuse to allow any cookies. And many users do refuse cookies or routinely delete them. Many users aren’t comfortable with the whole idea of a stranger storing things on their computers, especially files that remain after they leave the stranger’s Web site. It’s an understandable attitude. However, it definitely limits the use­ fulness of cookies. If your application depends on cookies and the user has turned off cookies, your application won’t work for that user.

Cookies were originally designed for storing small amounts of information for short periods of time. Unless you specifically set the cookie to last a longer period of time, the cookie will disappear when the user leaves your Web site. Although cookies are useful in some situations, you’re unlikely to need them for your Web database application for the following reasons:

Users may set their browsers to refuse cookies. Unless you know for sure that all your users will have cookies turned on or you can request that they turn on cookies (and expect them to follow your request), cookies are a problem. If your application depends on cookies, it won’t run if cookies are turned off.

PHP has features that work better than cookies. Beginning with PHP 4, PHP includes functions that create sessions and store information that’s available for the entire session. This session feature is more reliable and much easier to use than cookies for making information available to all the Web pages in a session. Sessions don’t work for long-term storage of information, but MySQL databases can be used for that.

You can store data in your database. Your application includes a database where you can store and retrieve data, which is usually a better solution than a cookie. Users can’t delete the data in your database unexpectedly. Because you’re using a database in this application, you can use it for any data storage needed, especially long-term data storage. Cookies are more useful for applications that don’t make use of a database.

You store cookies by using the setcookie function. The general format is

setcookie(“variable”,”value”);

The variable is the variable name, but do not include the dollar sign ($). This statement stores the information only until the user leaves your Web site. For instance, the following statement

setcookie(“state”,”CA”);

stores CA in a cookie variable named state. After you set the cookie, the information is available to your other PHP programs in the element of a built- in array as $_COOKIE[state]. You don’t need to do anything to get the infor­ mation from the cookie. PHP does this automatically. The cookie is not available in the program where it is set. The user must go to another page or redisplay the current page before the cookie information can be used.

The cookies are also available in an array called $HTTP_COOKIE_VARS with the variable names as keys. For instance, the value in the cookie set in the previous example can also be used as $HTTP_COOKIE_VARS[‘state’]. This built-in array must be used if you are using a version of PHP that is earlier than PHP 4.1.

If you want the information stored in a cookie to remain in a file on the user’s computer after the user leaves your Web site, set your cookie with an expira­ tion time, as follows:

setcookie(“variable”,”value”,expiretime);

The expiretime value sets the time when the cookie will expire. expire time is usually set by using either the time or mktime function as follows:

time: This function returns the current time in a format that the com­ puter can understand. You use the time function plus a number of sec­ onds to set the expiration time of the cookie, as shown in the following statements:

setcookie(“state”,”CA”,time()+3600); //expires in 1 hour setcookie(“Name”,$Name,time()+(3*86400)) // exp in 3 days

mktime: This function returns a date and time in a format that the com­ puter can understand. You must provide the desired date and time in the following order: hour, minute, second, month, day, and year. If any value is not included, the current value is used. You use the mktime function to set the expiration time of the cookie, as shown in the following statements:

setcookie(“state”,”CA”,mktime(3,0,0,4,1,2003));
//expires at 3:00 AM on April 1, 2003. setcookie(“state”,”CA”,mktime(12,0,0,,,));
//expires at noon today

You can remove a cookie by setting its value to nothing. Either of the follow­
ing statements removes the cookie:

setcookie(“name”);
setcookie(“name”,””);

The setcookie function has a major limitation, however. The setcookie function can only be used before any other output is sent. You cannot set a cookie in the middle of a program after you have echoed some output to the Web page. See the sidebar “Statements that must come before output,” else­ where in this chapter.

Passing information with HTML forms

The most common way to pass information from one page to another is by using HTML forms. An HTML form is displayed with a submit button. When the user clicks the submit button, the information in the form fields is passed to the program included in the form tag. The general format is

<form action=”processform.php” method=”POST”>
tags for one or more fields
<input type=”submit” value=”string”>
</form>

The most common use of a form is to collect information from users (which I discuss in detail in Chapter 8). However, forms can also be used to pass other types of information using hidden fields, which are added to the form and
sent with the information that the user typed in. In fact, you can create a form that has only hidden fields. You always need a submit button, and the new page doesn’t display until the user clicks the submit button, but you don’t need to include any fields for the user to fill in.

For instance, the following statements pass the user’s preferred background color to the next page when the user clicks a button named Next Page:

<?php
$color = “blue”; //passed via a user form
echo “<form action=’nextpage.php’ method=’POST’>
<input type=’hidden’ name=’color’ value=’$color’>
<input type=’submit’ value=’Next Page’>
</form>\n”;
?>

The Web page shows a submit button labeled Next Page, but it doesn’t ask
the user for any information. When the user clicks the button, nextpage.php
runs and can use the array element $_POST[color], which contains “blue”.

Using PHP Sessions

A session is the time that a user spends at your Web site. Users can view many Web pages between the time when they enter your site and then leave it. Often you want information to follow the user around your site so that it’s available on every page. PHP, beginning with version 4.0, provides a way to do this.

How PHP sessions work

PHP enables you to set up a session on one Web page and save variables as session variables. Then you open the session in any other page, and the ses­ sion variables are available for your use in the built-in arrays $_SESSION. To do this, PHP does the following:

1. Assigns a session ID number: The number is a really long, nonsense number that is unique for the user and that no one could possibly guess. The session ID is stored in a PHP system variable named PHPSESSID.

2. Stores session variables in a file on the server: The file is named with the session ID number. The file is stored in \tmp on Unix/Linux; in Windows, it’s stored in a directory called sessiondata under the direc­ tory where PHP is installed.

If you are the PHP administrator, you can change the location where the session files are stored by editing the configuration file php.ini. Find the setting for session.save_path and change the path to the location where you want to store the files.

3. Passes the session ID number to every page: If the user has cookies turned on, PHP passes the session ID using cookies. If the user has cook­ ies turned off, PHP passes the session ID in the URL for links or in a hidden variable for forms that use the post method.

4. Gets the variables from the session file for each new session page: Whenever a user opens a new page that is part of the session, PHP gets the variables from the file by using the session ID number that was passed from the old page and puts them into the built-in array
$_SESSION. You can use the array elements with the variable name as the key, and they have the value that you assigned in the previous page.

Sessions do not work unless track_vars is enabled. As of PHP 4.0.3,
track-vars is always turned on. For versions previous to 4.0.3, the option
--enable-track-vars should be used when installing PHP.

If users have cookies turned off, sessions do not work unless trans-sid is turned on. You find out how to turn trans-sid on and off later in the section, “Using PHP session variables.”

Opening sessions

You should open a session on each Web page. Open the session with the
session_start function, as follows:

session_start();

The function first checks for an existing session ID number. If it finds one, it sets up the $_SESSION array. If it doesn’t find one, it starts a new session by creating a new session ID number.

Because sessions use cookies if the user has them turned on, session_start is subject to the same limitation as cookies. That is, the session_start func­ tion must be called before any output is sent. For complete details, see the sidebar “Statements that must come before output,” elsewhere in this chapter.

You can tell PHP that every page on your site should automatically start
with a session_start. To do this, edit the configuration file php.ini. If you are the PHP administrator, you can edit this file; otherwise, ask the adminis­ trator to edit it. Look for the variable session.auto_start and set its value to 1. You might have to restart the Web server before this takes effect. With auto_start turned on, you don’t need to add a session_start at the begin­ ning of each page.

Using PHP session variables

When you want to save a variable as a session variable — that is, available to other Web pages that the user might visit — save it in the $_SESSION array as follows:

$_SESSION[‘variablename’] = value;

The variable value is then available in the $_SESSION array on other Web pages. For example, you can store the state where the user lives by using the following statement:

$_SESSION[‘state’] = “CA”;

You can then use $_SESSION[‘state’] in any other Web page, and it will have the value CA.

The following two programs show how to use sessions to pass information from one page to the next. The first program, sessionTest1.php in
Listing 9-2, shows the first page where the session begins. Listing 9-3 shows the program sessionTest2.php for the second page in a session.

Listing 9-2: Starting a Session

<?php session_start();
?>
<html>
<head><title>Testing Sessions page 1</title></head>
<body>
<?php
$_SESSION[‘session_var’] = “testing”;
echo “This is a test of the sessions feature.
<form action=’sessionTest2.php’ method=’POST’>
<input type=’hidden’ name=’form_var’
value=’testing’>
<input type=’submit’ value=’go to next page’>
</form>”;
?>
</body></html>

Notice that two variables are set in this program to be passed to the second page. The session variable session_var is created. In addition, a form is dis­ played with a hidden variable form_var, which is also passed to the second page when the submit button is pressed. Both variables are set to “testing”.

Listing 9-3: The Second Page of a Session

<?php session_start();
?>
<html>
<head><title>Testing Sessions page 2</title></head>
<body>
<?php
echo “session_var = {$_SESSION[‘session_var’]}<br>\n”;
echo “form_var = {$_POST[‘form_var’]}<br>\n”;
?>
</body></html>

Point your browser at sessionTest1.php and then click the submit button that reads Go to Next Page. You will then see the following output from sessionTest2.php:

session_var = testing form_var = testing

Because sessions work differently for users with cookies turned on and for users with cookies turned off, you should test the two programs in both con­ ditions. To turn off cookies in your browser, you change the settings for options or preferences.

To disable cookies in Internet Explorer, follow these steps:

1. Choose Tools➪Internet Options.

The Internet Options dialog box opens.

2. Click the Security tab in IE 5.5 or the Privacy tab in IE 6.

3. Click the Internet icon to highlight it.

4. Click the Custom Level button.

The Security Settings dialog box appears.

5. Scroll down to the Cookies section and select Disable for each of the cookie settings.

6. Click OK.

To disable cookies in Netscape Navigator, follow these steps:

1. Choose Edit➪Preferences.

2. Highlight Advanced.

3. Mark Disable Cookies.

4. Click OK.

If the output from sessionTest2 shows a blank value for $session_var when you turn cookies off in your browser, it is probably because trans-sid is not turned on. You can turn on trans-sid in your php.ini file. Find the following line:

session.use_trans_sid = 0

Change the 0 to 1 to turn on trans-sid. If you can’t get this problem fixed, you can still use sessions, but you must pass the session ID number in your programming statements because PHP won’t pass it automatically when cookies are turned off. For details on how to use sessions when trans-sid is not turned on, check out the next section.

For PHP 4.1.2 or earlier, trans-sid is not available unless it was enabled by using the option —enable-trans-sid when PHP was compiled.

Sessions without cookies

Many users turn off cookies in their browsers. PHP checks the user’s browser to see whether cookies are allowed and behaves accordingly. If the user’s browser allows cookies, PHP does the following:

Sets the variable $PHPSESSID equal to the session ID number

Uses cookies to move $PHPSESSID from one page to the next

If the user’s browser is set to refuse cookies, PHP does the following:

Sets a constant called SID. The constant contains a variable=value
pair that looks like PHPSESSID=longstringofnumbers.

Might or might not move the session ID number from one page to the next, depending on whether trans-sid is turned on. If it is turned on, PHP passes the session ID number; if it is not turned on, PHP does not pass the session ID number.

Turning on trans-sid has advantages and disadvantages. The advantage is that sessions work seamlessly even when users turn cookies off. It also is much easier to program sessions with trans-sid turned on. The disadvantage is
that the session ID number is often passed in the URL. In some situations, the session ID number should not be shown in the browser address. Also, when the session ID number is in the URL, it can be bookmarked by the user. Then, if the user returns to your site by using the bookmark with the session ID number in it, the new session ID number from the current visit can get con­ fused with the old session ID number from the previous visit and possibly cause problems.

Sessions with trans-sid turned on
When trans-sid is turned on and the user has cookies turned off, PHP auto­ matically sends the session ID number in the URL or as a hidden form field. If the user moves to the next page by using a link, a header function, or a form with the get method, the session ID number is added to the URL. If the user moves to the next page by using a form with the post method, the session ID number is passed in a hidden field. PHP recognizes $PHPSESSID as the ses­ sion ID number and handles the session without any special programming on your part.

The session ID number is only added to the URLs for pages on your own Web site. If the URL of the next page includes a server name, PHP assumes that
the URL is on another Web site and doesn’t add the session ID number. For instance, if your link statement is

<a href=”newpage.php”>

PHP will add the session ID number. However, if your statement is

<a href=”HTTP://www.company.com/newpage.php”>

PHP will not add the session ID number.

Sessions without trans-sid turned on
When trans-sid is not turned on, PHP does not send the session ID number to the next page when users have cookies turned off. Rather, you must send the session ID number yourself.

Fortunately, PHP provides a constant that you can use to send the session ID yourself. A constant is a variable that contains information that can’t be changed. (Constants are described in Chapter 6.) The constant that PHP pro­ vides is named SID and contains a variable=value pair that you can add to the URL, as follows:

<a href=”nextpage.php?<?php echo SID?>” > next page </a>

This link statement adds a question mark (?) and the constant SID to the URL. SID contains the session ID number formatted as variable=value. The output from echo SID looks something like this:

PHPSESSID=877c22163d8df9deb342c7333cfe38a7

Therefore, the URL that is sent is

<a href=”nextpage.php?PHPSESSID=877c22163d8df9deb342c7333cfe38a7>
next page </a>

For one of several reasons (which I discuss in the section “Adding informa­ tion to the URL,” earlier in this chapter), you may not want the session ID number to appear on the URL shown by the browser. To prevent that, you can send the session ID number in a hidden field in a form by using the post method. First, get the session ID number; then send it in a hidden field. The statements to do this are

<?php
$PHPSESSID = session_id();
echo “<form action=’nextpage.php’ method=’POST’>
<input type=’hidden’ name=’PHPSESSID’
value=’$PHPSESSID’>
<input type=’submit’ value=’Next Page’>
</form>”;
?>

These statements do the following:

1. Store the session ID number in a variable called $PHPSESSID. Use the function session_id, which returns the current session ID number.

2. Send $PHPSESSID in a hidden form field.

On the new page, PHP will automatically use $PHPSESSID to get any session variables without any special programming needed from you.

Making sessions private

PHP session functions are ideal for Web sites that are restricted and require users to log in with a login name and password. Those Web sites undoubtedly have many pages, and you don’t want the user to have to log in to each page. PHP sessions can keep track of whether the user has logged in and refuse access to users that aren’t logged in. You can use PHP sessions to do the following:

1. Show users a login page.

2. If a user logs in successfully, set and store a session variable.

3. Whenever a user goes to a new page, check the session variable to see whether the user has logged in.

4. If the user has logged in, show the page.

5. If the user has not logged in, bring up the login page.

To check whether a user has logged in, add the following statements to the top of every page:

<?php session_start()
if ( @$_SESSION[‘login’] != “yes” )
{
header(“Location: loginPage.php”);
exit();
}
?>

In these statements, $_SESSION[login] is a session variable that is set to “yes” when the user logs in. The statements check whether
$_SESSION[login] is equal to “yes”. If it is not, the user is not logged in and is sent to the login page. If $_SESSION[login] equals “yes”, the program proceeds with the rest of the statements on the Web page.

Closing PHP sessions

For restricted sessions that users log into, you often want users to log out when they’re finished. To close a session, use the following statement:

session_destroy();

This statement gets rid of all the session variable information that is stored in the session file. PHP no longer passes the session ID number to the next page. However, the statement does not affect the variables currently set on the current page: They still equal the same values. If you want to remove the variables from the current page — as well as prevent them from being passed to the next page — unset them with this statement:

unset($_SESSION );

0 comments: