- Table of Contents
- Copyright
- About the Author
- Acknowledgments
- Tell Us What You Think!
- Introduction
- Part I: Introduction to Mac OS X
- Chapter 1. Mac OS X Component Architecture
- Chapter 2. Installing Mac OS X
- Chapter 3. Mac OS X Basics
- Chapter 4. The Finder: Working with Files and Applications
- Chapter 5. Running Classic Mac OS Applications
- Part II: Inside Mac OS X
- Chapter 6. Native Utilities and Applications
- Chapter 7. Internet Communications
- Chapter 8. Installing Third-Party Applications
- Part III: User-Level OS X Configuration
- Chapter 9. Network Setup
- Chapter 10. Printer and Font Management
- Chapter 11. Additional System Components
- Part IV: Introduction to BSD Applications
- Chapter 12. Introducing the BSD Subsystem
- Chapter 13. Common Unix Shell Commands: File Operations
- Part V: Advanced Command-Line Concepts
- Chapter 14. Advanced Shell Concepts and Commands
- Chapter 15. Command-Line Applications and Application Suites
- Chapter 16. Command-Line Software Installation
- Chapter 17. Troubleshooting Software Installs, and Compiling and Debugging Manually
- Chapter 18. Advanced Unix Shell Use: Configuration and Programming (Shell Scripting)
- Part VI: Server/Network Administration
- Chapter 19. X Window System Applications
- Chapter 20. Command-Line Configuration and Administration
- Chapter 21. AppleScript
- Chapter 22. Perl Scripting and SQL Connectivity
- Chapter 23. File and Resource Sharing with NetInfo
- Chapter 24. User Management and Machine Clustering
- Chapter 25. FTP Serving
- Chapter 26. Remote Access and Administration
- Chapter 27. Web Serving
- Part VII: Server Health
- Chapter 28. Web Programming
- Chapter 29. Creating a Mail Server
- Chapter 30. Accessing and Serving a Windows Network
- Chapter 31. Server Security and Advanced Network Configuration
- Chapter 32. System Maintenance
- Appendix A. Command-Line Reference
- Appendix B. Administration Reference
PHP
PHP, the PHP Hypertext Preprocessor (it's recursive), is a relatively new language that integrates with the Apache Web server. Whereas Perl is a general-purpose programming language, PHP provides Web-specific functions that can speed up development time significantly.
One of the primary differences between Perl and PHP is how it is programmed. With Perl, the focus is on the application logic; integrating an interface is secondary. When using PHP, the logic is embedded into the HTML. A PHP developer can use traditional Web development tools, such as Macromedia Dreamweaver or Adobe GoLive, to create an interface, and then attach logic. For example, in Perl, we used code like this to print a variable within some HTML:
print <<HTML;
print "<TR>";
print "<TD align=\"center\">$myname</TD>";
print "</TR>";
HTML
The equivalent code in PHP looks like this:
<TR> <TD align="center"><?php print $myname; ?></TD> </TR>
As you can see, the application code is entirely isolated from the HTML. PHP code is contained with its own tags: <?php to start and ?> to end. As Apache reads a PHP file, it executes the code in the PHP tags, and then sends the final result to the waiting browser. The remote user cannot see these special tags in the HTML source—your application logic is safe from prying eyes. In addition to a clean programming model, PHP offers features such as built-in database access, advanced security, and real-time graphic generation.
Installing PHP
If you've poked around through the files on your system, you might have noticed that there is a PHP folder installed with Mac OS X (path: /System/Library/PHP). Unfortunately, with the initial release of Mac OS X, this PHP distribution is inherently broken. I don't recommend that you try to get it running; the result will be a partially functioning, bug-ridden version of PHP. So, the first step in using PHP is getting it installed. Before starting, make sure that you su to root, or execute the commands shown here using sudo.
First, download the latest PHP distribution from www.php.net/downloads.php and unarchive it:
[primal:~] jray% tar zxf php-4.0.5.tar.gz
Next, download the support files from Stepwise.com that will enable compilation on Mac OS X. The 4.0.5 distribution of PHP has a few errors that require an additional script to work around. This is likely to change in the future. The 4.0.4pl1 release of PHP did not suffer from this problem. You can download the 4.0.5 patch from http://graphics.stepwise.com/articles/workbench/php-4.0.5-genif.sh.
The download, php-4.0.5-genif.sh, should be moved to build/genif.sh within the php 4.0.5 directory. This will replace an existing genif.sh file:
[primal:~/php-4.0.5] jray% mv php-4.0.5-genif.sh build/genif.sh
cd into the distribution directory and use ./configure --with-apxs --with-xml to prepare the software for compilation.
[primal:~] jray% cd php-4.0.5
^C[primal:~/php-4.0.5] jray% sudo ./configure --with-apxs --with-xml
loading cache ./config.cache
checking for a BSD compatible install... (cached) /usr/bin/install -c
checking whether build environment is sane... yes
checking whether make sets ${ MAKE} ... (cached) yes
checking for working aclocal... missing
checking for working autoconf... found
checking for working automake... missing
checking for working autoheader... found
...
You might want to run ./configure --help to see other compilation options. By default, PHP includes MySQL support along with all base functions discussed in this chapter. For extended features, such as Flash generation, PostgreSQL support, and so on, you'll need to enable these options during the install step.
Next, use make to compile the software:
[primal:~/php-4.0.5] jray% sudo make Making all in Zend /bin/sh ../libtool --silent --mode=compile cc -DHAVE_CONFIG_H -I. -I. -I../main-traditional-cpp -DSUPPORT_UTF8 -DXML_BYTE_ORDER=21 - -g -O2 -c zend_language_scanner.c /bin/sh ../libtool --silent --mode=compile cc -DHAVE_CONFIG_H -I. -I. -I../main -
-traditional-cpp -DSUPPORT_UTF8 -DXML_BYTE_ORDER=21 - -g -O2 -c zend_ini_scanner.c /bin/sh ../libtool --silent --mode=link cc -g -O2 -o libZend_c.la -zend_language_scanner
.lo zend_ini_scanner.lo ...
After a few minutes, the compilation will finish. The software is now ready to be installed, so use make install to complete the process:
[primal:~/php-4.0.5] jray% sudo make install Making install in Zend make[2]: Nothing to be done for `install-exec-am'. make[2]: Nothing to be done for `install-data-am'. Making install in main make[2]: Nothing to be done for `install-p'. ...
Next, copy the default PHP configuration file into its final location:
[primal:~/php-4.0.5] jray% cp php.ini-dist /usr/local/lib/php.ini
If you'd like to fine-tune the PHP configuration, open /usr/local/lib/php.ini.
First, make sure that any system-specific settings are set. Usually, the default settings work perfectly fine. You might want to look at the resource settings, however, because they can be used to make sure that renegade scripts don't eat up the memory and CPU time on your system. Look in the php.ini for these lines:
;;;;;;;;;;;;;;;;;;; ; Resource Limits ; ;;;;;;;;;;;;;;;;;;; max_execution_time = 30 ; Maximum execution time of each script, in seconds memory_limit = 8M ; Maximum amount of memory a script may consume (8MB)
By default, scripts might use up to 8MB of memory and take 30 seconds to execute. For many CGIs, these are rather liberal values. You can reduce them as you'd like; I've cut them in half on my system and haven't had any problems thus far.
Additionally, you should enable safe mode (safe_mode = On) on a public-use production server. This virtually eliminates the need to worry about environment variables being modified and misused:
; Safe Mode
safe_mode = On
safe_mode_allowed_env_vars = PHP_ ; Setting certain environment variables
; may be a potential security breach.
; This directive contains a comma-delimited
; list of prefixes. In Safe Mode, the
; user may only alter environment
; variables whose names begin with the
; prefixes supplied here.
; By default, users will only be able
; to set environment variables that begin
; with PHP_ (e.g. PHP_FOO=BAR).
; Note: If this directive is empty, PHP
; will let the user modify ANY environment
; variable!
safe_mode_protected_env_vars = LD_LIBRARY_PATH; This directive is a comma-
; delimited list of environment variables,
; that the end user won't be able to
; change using putenv().
; These variables will be protected
; even if safe_mode_allowed_env_vars is
; set to allow to change them.
disable_functions = ; This directive allows you to disable certain
; functions for security reasons. It receives
; a comma separated list of function names.
; This directive is *NOT* affected by whether
; Safe Mode is turned on or off.
This combination of settings enables you, the administrator, to prohibit environment variables from being modified unless they begin with one of the listed prefixes (safe_mode_protected_env_vars). You can also specify environment variables that, under no circumstances, should ever be allowed to change, regardless of the prefix settings. Finally, if there are certain functions you'd rather not be available to users, you can list these here as well (disable_functions).
The final step is enabling the PHP module in Apache, which consists of nothing more than uncommenting a few lines in your /private/etc/httpd/httpd.conf:
LoadModule php4_module libexec/httpd/libphp4.so AddModule mod_php4.c
and
AddType application/x-httpd-php .php AddType application/x-httpd-php-source .phps
Search the existing httpd.conf file and remove the # (comment) character from in front of each of these lines. To activate the changes, restart the Apache Web server using the Sharing Preference panel, or by typing sudo /usr/sbin/apachectl restart from the command line.
To verify that PHP is working, create a file (test.php) within one of your Web directories:
<?php phpinfo(); ?>
Load this test page using a Web browser. If the installation was successful, you should see a screen similar to Figure 28.8.
Figure 28.8 The phpinfo() function generates a screen of PHP installation information.
PHP Syntax
The best introduction to programming PHP is a background in C or Perl. Check out Chapter 22 as a starter guide for that language. PHP borrows heavily from Perl's free-form open scripting model and auto data conversion. What truly makes PHP shine is the built-in Web functions. Let's take a brief look at what you need to get you started, then examine some of the unique features.
Syntax
PHP programs are created as standard text files within any of your Web-enabled directories. To execute, the script you must have the extension .php. This does not have a bearing on the HTML contents of the file. In fact, you can have an HTML file that contains no PHP code, but ends in .php—it will still be served correctly, albeit with a slight performance penalty as the server checks the file for executable code.
PHP code itself is typically embedded within the <?php and ?> brackets. Failing to place these tags around code will result in the programming being interpreted as text within an HTML document. Even if you are working with a file that contains no HTML at all, it must still place all the PHP script within the brackets. There can be multiple PHP start and end tags in a single document.
If you've written JavaScript, this is similar to the behavior of the <script> and </script> tags that embed JavaScript code into a document. Regardless of how many PHP code segments are in your program, the code can be considered all part of one big global block. The variables that are defined in one section are available in another. For example:
<?php $myname="John"; ?> This is some standard HTML in the middle...<BR><BR> <?php print $myname; ?>
This code fragment assigns the value John to $myname, and then includes a bit of HTML, and finally prints the value of $myname (John). Even though $myname occurs within two separate PHP blocks, the value is still maintained.
Each line of PHP code must end in a semicolon (;) to be correctly executed. Because of this requirement, extremely long lines of code can be broken across multiple lines to improve legibility.
Data Types
Like Perl, PHP's data types are typecast from one to another internally. Although there is one primary data type, PHP is an object-oriented language and is used to create arbitrary object types with their own properties. Object-oriented programming is beyond the scope of this text, so only the basics will be covered here—don't worry, there's more than enough to start building complex Web applications.
- $ <variable name> — PHP defines a variable as an alphanumeric string prefaced by a $. Variable names cannot begin with a number. The variable can contain text, binary data, numbers, and so on. Type conversion happens automatically during program execution.
- $ <variable name> [ <index> ]— Arrays offer more flexibility than Perl. An array can be defined during the course of program execution by adding an [index] to the end of a variable name. Unlike Perl, which differentiates between a standard array and associative arrays, an array index in PHP can be either a number or a string.
PHP variables are unique creatures and can be used in very interesting ways. For example, the contents of a variable can be interpreted as variables themselves. Assume that you have a variable named $peach. Obviously, you can reference this variable by name ($peach). Now assume that a second variable, $fruit, contains the string peach "peach". Using this second variable, you can reference the contents of the first variable through $$fruit. This works because $$fruit is functionally identical to typing $"peach", which in turn is equivalent to $peach. This same technique can be applied to function calls to create a logic flow that changes itself based on variables in the program.
Basic Operators
The comparison and assignment operations work much like a simplified version of their Perl counterparts. The primary difference is that string comparisons are identical to numeric comparisons in syntax within PHP. Table 28.1 contains the common PHP operators.
Table 28.1. Common PHP Operators
| Operator | Action | Description |
| == | Equals | Tests for equality |
| != | Not equal | Tests for inequality |
| = | Assignment | Assigns the value on the right to the variable on the left |
| * | Multiplication | Multiplies two values together |
| / | Division | Divides two values |
| + | Addition | Adds two numbers together |
| - | Subtraction | Subtracts one number from another |
| . | Concatenation | Concatenates two strings together |
| && | AND | Performs a logical AND on two values |
| || | OR | Performs a logical OR on two values |
As previously mentioned, PHP automatically handles type conversions for you, making it possible to write code that looks like this:
<?php $a="1"; $b="3"; $c=$a.$b; $c=$c*2; ?>
Here, two strings, 1 and 3, are concatenated together and stored in $c. This new value is then multiplied by 2. Printing the result would display 26—even though the only true number used in the calculation was 2 (during the multiplication).
There are a few shortcuts to the assignment as well. For example, incrementing or decrementing a number is very common. Written in long form, adding 1 to the existing value of a variable $a looks like this:
$a=$a+1;
This can be shortened to
$a++;
The same applies to subtraction, using the minus (-) symbol.
Another shortcut applies to concatenating, adding, or subtracting to an existing value. For example, this line of code concatenates $b onto the end of $a:
$a=$a.$b;
The same thing can be written as
$a.=$b;
For addition and subtraction, just substitute in the appropriate operator in place of .. The basic syntax remains the same.
Control Structures
Two types of control structures will be discussed here: linear flow operators and looping constructs. Linear flow operators can change the course of a program based on variables and other conditions. Looping constructs, on the other hand, can repeat sections of code based on similar criteria. Together they enable software to adapt to a particular task, rather than being hard-coded to work with one set of input.
if-then-else
The most common linear flow control structure is the if-then-else statement. This can evaluate one or more conditions and act on them accordingly. The basic PHP if-then statement is structured like this:
if <condition> {
<do something>;
}
This statement can be expanded to include an alternative course of action if the original condition is not met. This is considered an if-then-else statement:
if <condition> {
<do something>;
} else {
<do something else>;
}
One final variation of the statement exists that can evaluate multiple conditions within the single statement. This last variation is the if-then-elsif statement.
if <condition> {
<do something>;
} elsif <another condition> {
<do something else>;
} else {
<do yet another thing>;
}
This example includes a single elsif line, but, depending on the needs of the programmer, this can be repeated as many times as he or she feels necessary. A less verbose way to accomplish the same goal is to use the switch statement.
switch
The switch statement takes a value as input, and defines a set of possible outcomes that can occur, depending on that value. The best way to understand how this works is to take a look at an example:
switch ($x) {
case 0:
print "x=0";
break;
case 1:
print "x=1";
break;
case 2:
print "x=2";
break;
default:
print "none of the above";
break;
}
This piece of code examines the value of $x. If it is 0, PHP prints x=0. If $x equals 1, the code prints x=1… and so on. If $x doesn't match any of the listed values (0, 1, 2), it uses the default value and prints none of the above.
The switch statement can be extended to include as many cases as needed. In addition, the cases do not have to be numeric. You can just as easily include strings:
switch ($name) {
case 'John':
print "John has a dog named Maddy";
break;
case 'Robyn':
print "Robyn has a dog named Coco";
break;
case 'Jack':
print "Jack has a bag of M&Ms";
break;
case default:
print "I don't know you!";
break;
}
The two portions of the switch statement that might require a bit more explanation are the break statement and the default case.
The break causes the switch statement to exit. If break is not executed, all code after the matching case is executed. If John is matched, all the print statements are executed until a break is encountered.
The default case is optional. It is executed only if none of the other cases is matched. It's usually a good idea to have a default case to keep untrapped errors from occurring.
for
The for loop is the most commonly encountered loop in programming, regardless of the language. This loop executes a block of code until a condition is met. Each iteration of a for-next loop increments (or decrements) a counter variable. The loop is constructed using this syntax:
for (<initialization>;
<execution condition>;
<increment>) {
<code block>
}
The initialization sets up the loop and initializes the counter variable to its default state. The execution condition is checked in each iteration of the loop; if it evaluates to false, the loop ends. Finally, the increment is a piece of code that defines an operation performed on the counter variable each time the loop is run. For example, the following loop counts from 0 to 9:
for ($count=0;$count<10;$count++) {
print "Count = $count";
}
The counter, $count, is set to 0 when the loop starts. With each repetition, it is incremented by 1 ($count++). The loop exits when the counter reaches 10 ($count<10).
The format for the PHP for loop is identical to the Perl syntax.
while
The while loop executes while a condition evaluates to true. Unlike a for loop, which usually ends based on a change in the counter, the while loop requires that something change within the code block that will cause the condition to evaluate as false.
while (<execution condition>) {
<code block>
}
The previous for example counted from 0 to 9. This same loop translated into a while loop looks like this:
$count=0;
while ($count<10) {
print "Count = $count";
$count++;
}
When using while/do-while loops, be sure that the execution condition will eventually evaluate to false. It's easy to write infinite loops using this structure.
do-while
Similar to the basic while loop, a do-while loop runs until a preset condition evaluates to false. The difference between the two loop styles is where the execution condition is checked. In a while loop, the condition is evaluated at the start of the loop. Do-while loops, on the other hand, evaluate the condition at the end:
do {
<code block>
} while (<execution condition>);
Again, let's translate the count from 0 to 9 into a do-while loop. As you can see, the difference is slight.
$count=0;
do {
print "Count = $count";
$count++;
} while ($count<10);
Functions
Like any good programming language, PHP supports the notion of functions—independent pieces of code that can act on input and return a result. As you develop Web applications, you'll find that a reasonable amount of code is reused each time. If applications are programmed as modularly as possible, you can create a library of commonly used functions to share among multiple applications and developers.
A function is set up using the function keyword; values are returned to the main program using return. For example:
function addnumbers($arg1,$arg2) {
$result=$arg1+$arg2;
return($result);
}
This function accepts two arguments ($arg1 and $arg2), adds them together, and then returns the result to the main program. The addnumbers function could be called like this:
$theresult=&addnumbers(1,5);
In this example, the function is called with a preceding ampersand (&). This is optional, but is required in code where the function's definition occurs after the function call is used in the code.
By default, all variables used in a function are automatically considered local to that function and cannot be accessed outside of the function code. To make a variable's scope global, use the global keyword within a function:
global <variable name>;
A variable that is declared global can be accessed from the main program block as well as the declaring function.
Common Functions
It's pointless to try and document all PHP's capabilities in this chapter. There are more than 1,500 functions available in the PHP 4.0.6 release. Table 28.2 provides a quick reference to some of the more interesting and useful functions. For those of you interested, when compiling this list I surveyed more than a dozen PHP scripts and noted the most frequently used operations as well as those needed for the examples in the chapter.
Table 28.2. With More Than 1,500 Available Functions, PHP Is Anything but Limited
| Function | Purpose |
| addslashes( <string> ) | Escapes special characters within strings (such as '"') and returns the resulting string. |
| chop( <string> ) | Removes trailing white spaces from a string and returns the result. |
| file( <url> ) | Reads a file from a URL (local, FTP, Web) and returns an array of each line in the file. |
| header( <string> ) | Outputs a header before processing any HTML output. |
| join( <glue string>, <array> ) | Returns a single string containing all the elements of a given array joined together with the "glue" string. Same as implode. |
| preg_replace( <regex>, <replace string>,<string> ) | Searches a string for a Perl-style regular expression, replaces it with another, and returns the new string. |
| print " <output>" | Displays an output string. This is identical to the echo keyword. |
| opendir( <directory name> ) | Opens a directory for reading and returns a file handle. |
| readdir( <file handle> ) | Returns the next filename within a directory opened with opendir. Returns false if no more files are available. |
| require( <filename> ) | Includes the contents of another file within the PHP code. |
| session_start() | Initializes a new session. |
| session_register ( <variable> ) | Registers a variable with a session—making it available in subsequent Web page accesses. Do not include the $ with the name of the variable. |
| session_unregister ( <var i able> ) | Unregisters a session variable. |
| session_destroy() | Removes the active session. |
| sort( <array>) | Sorts an array. |
| soundex( <string> ) | Returns a soundex value for a given string. This value is based on the sound of a string and can be used to compare two strings that sound similar but are spelled differently. |
| split( <pattern> , <string> ) | Splits a string based on the characters in <pattern> and returns each of the results as the element in an array. |
| stripslashes( <string> ) | Removes slashes from a string—the opposite of addslashes—and returns the result. |
| strlen( <string> ) | Returns the length of a given string. |
Visit www.php.net/quickref.php for a full list of the PHP functions.
PHP in Practice
In the Perl portion of this chapter, we created a simple image catalog. Let's see how that catalog can be rewritten in PHP. Listing 28.10 shows a PHP version of the Perl-image catalog.
Example 28.10. The Image Catalog, Rewritten in PHP
1: <?php if (!$imagedir) { ?>
2: <form action="showimages1.php" method="post">
3: Choose image dir: <input type="text" name="imagedir" value="imagefolder"><br>
4: Select the number of columns in the display: <select name="columns">
5: <option>1</option>
6: <option>2</option>
7: <option>3</option>
8: <option>4</option>
9: </select><br>
10: Show images that match: <input type="text" name="match">
11: <input type="submit" name="submit">
12: </form>
13: <?php exit; } ?>
14:
15: <TABLE BGCOLOR="#FFFFFF" BORDER="1" BORDERCOLOR="#000000">
16: <?php
17: $handle=opendir("$imagedir");
18: while ($imagename = readdir($handle)) {
19: if ($count==0 && $loop==0) { print "<TR>"; $loop=1; }
20: if (preg_match("/.*$match.*\.jpg$/i",$imagename)) { ?>
21: <TD align=center>
22:<IMG SRC="<?php print"$imagedir/$imagename"; ?>" width="120" height="90"><br>
23: <FONT TYPE="Arial"><?php print $imagename; ?>
24: </TD><?php
25: $count++;
26: if ($count==$columns) { print "</TR>"; $count=0; $loop=0; }
27: }
28: }
29: if ($count!=0) { print "</TR>"; }
30: ?>
31: </TABLE>
The first two things you should notice looking at this code are that it is shorter and that the PHP is embedded in the HTML, rather than the HTML being embedded in the programming.
As the PHP application begins sending output, it automatically adds a text/html content-type header. In addition, no external library, such as cg i input.pl, is required. When a form posts information to a PHP program, the form variables are automatically translated into PHP variables. For example, an input field with the name address becomes the variable $address when submitted to a PHP script. These shortcuts enable you to focus on the code, rather than the specifics of HTTP.
A breakdown of the changes in the code follows:
Lines 1–13 check whether the variable $imagedir is defined. If it isn't, the user hasn't submitted a search request yet and the search form should be displayed. Unlike Perl, which used print to show the form, PHP if-then tags can encompass HTML blocks. In this case, if the variable isn't defined, the HTML in the if-then is sent to the browser—otherwise, it is skipped.
Line 15 starts the HTML output table. Line 17 opens the image directory for reading. PHP, sadly, doesn't support a glob function, like Perl. While there are files in the opened directory, lines 18–28 read them into $filename.
If at the start of a row, send a <TR> tag. Line 19 must also set a flag ($loop) to indicate that the loop has started—this prevents multiple <TR> from being sent if the first few files read in the directory are not image files. Line 20 uses a Perl regular expression to match the filename to a file that ends in .jpg and includes the search string ($match).
Lines 21–24 display the table data cell for the image. Note that the image name is added to the HTML by embedded PHP print statements. Lines 25–26 increment the number of images displayed. If it is equal to the selected number of image columns, output a </TR>.
If the last file displayed occurred in the middle of a row, the program must add a final </TR> to close the row. This is done with line 29. Line 31 closes the output table.
For the most part, the programming syntax should closely resemble what you've seen in Perl. The lack of a glob function adds a few extra lines, but doesn't prevent the PHP version from coming in 20% shorter.
You might have noticed that this version of the script does not attempt to check the input variables for /. This is because PHP automatically escapes troublesome characters in user input. For example, /example becomes \/example. This gives developers some peace of mind during programming.
PHP and Sessions
I've made such a big deal about sessions and how they make life easier; it's probably time to see one in use. Unfortunately, it's very difficult to fabricate the use for a session in a reasonable amount of space. So, let's take a look at a simple case of sessions at work.
Imagine having a Web page that remembers how many times you've visited it during your current browser session (since you last quit out of your Web browser). This can't be done using a form because an action would be needed to submit the form each time you load the page. URL parameters can't be used because, likewise, the page would have to alter all the links it contains to include the number of visits using URL variable passing. With sessions, this is beyond simple. In fact, the following example keeps track of the cumulative number of visits to two distinct pages.
Create two Web pages (one.php and two.php) that link to one another. In one.php, type the following:
<?php session_start(); $x++; session_register(x); print "You've been to page one and two $x times"; ?> <BR> <A HREF="two.php">Go to page two</A>
And in two.php, type this:
<?php session_start(); $x++; session_register(x); print "You've been to page one and two $x times"; ?> <BR> <A HREF="one.php">Go to page one</A>
Loading one of the pages (either one) creates a page similar to that shown in Figure 28.9.
Figure 28.9 The two Web pages (one.php and two.php) share a single variable $x.
Clicking the link to toggle between the two pages increments the counter and the displayed number starts counting up. Although this is not a groundbreaking Web site, it demonstrates the capabilities of built-in session management. The two pages share a single counter variable $x. The session_start() command starts a new PHP session, if one doesn't already exist. The session_register(x) registers the variable $x with the current session—effectively saving its value until another page is accessed. It is important to provide variables to se s sion_register without the preceding dollar sign ($).
The incrementing of $x doesn't depend in any way on the links between one.php and two.php. You can reload one of the pages 30 times and the counter will increment 30 times. You can even visit another Web site, then come back to either of the Web pages and the count is still present. The only way to lose the value of $x is to drop the session—that is close your Web browser.
The virtues of PHP could be touted for pages and pages, but, unfortunately, the room is not available. If you'd like more information on PHP development, I urge you to look at any of these fine sites:
- PHP Homepage— www.php.net/
- PHP Builder— www.phpbuilder.net/
- PHPHead— www.phphead.net/
- The PHP Resource— www.php-resource.de/
- PHPInfo— www.phpinfo.net
Alternative Development Environments | Next Section

Account Sign In
View your cart