Page 368 - Beginning PHP 5.3
P. 368
Part III: Using PHP in Practice
Next comes the main decision logic of the script. This code examines the $_POST and $_GET superglobal
arrays and, depending on what field it finds, it calls an appropriate function to handle the request:
if ( isset( $_POST[“saveFile”] ) ) {
saveFile();
} elseif ( isset( $_GET[“filename”] ) ) {
displayEditForm();
} elseif ( isset( $_POST[“createFile”] ) ) {
createFile();
} else {
displayFileList();
}
If the saveFile form field was submitted, the user wants to save his edits, so the saveFile() function
is called. If the filename field was found in the query string, the user has clicked a file to edit in the list;
displayEditForm() is called to let the user edit the file. If the createFile form field was found, the
user has clicked the Create File button to make a new file, so createFile() is called to create the new
file. Finally, if none of these fields exist, the file list is displayed by calling displayFileList() .
The displayFileList() Function
When the user first runs the application, displayFileList() is called to display the list of files to edit,
along with a form field to allow the user to add a new file (Figure 11 - 4). This function accepts one
optional argument, $message , containing any error message to display to the user in the form.
First the function calls the displayPageHeader() helper function (described in a moment) to generate
a standard page header. Next it checks that the text files directory exists (if not, the script exits with an
error message) and attempts to open the directory and retrieve a Directory object by calling the dir()
function (again, if there ’ s a problem the script exits):
displayPageHeader();
if ( !file_exists( PATH_TO_FILES ) ) die( “Directory not found” );
if ( !( $dir = dir( PATH_TO_FILES ) ) ) die( “Can’t open directory” );
After displaying any error message passed to the function, and kicking off an HTML table to display the
file list, the function uses a while construct along with calls to the $dir - > read() method to loop
through the entries in the text files directory. For each entry, the script checks that the entry ’ s filename is
not “ . ” or “ .. ” , and that the file isn ’ t a directory and its filename extension is “. txt . If the entry
”
matches all these criteria, it is displayed as a row in the table. Notice that the loop stores the complete
path to each file in a temporary $filepath variable for convenience:
while ( $filename = $dir- > read() ) {
$filepath = PATH_TO_FILES . “/$filename”;
if ( $filename != “.” & & $filename != “..” & & !is_dir( $filepath ) & &
strrchr( $filename, “.” ) == “.txt” ) {
echo ‘ < tr > < td > < a href=”text_editor.php?filename=’ . urlencode
( $filename ) . ‘” > ’ . $filename . ‘ < /a > < /td > ’;
330
9/21/09 9:10:22 AM
c11.indd 330 9/21/09 9:10:22 AM
c11.indd 330