PHP for the World Wide Web (Visual QuickStart Guide)

I l @ ve RuBoard

Now that you've coded a script that writes data to a file, it's time to create one that can read that information. Reading data from a file is almost as easy as its writing counterpart . There are, again, three steps. First you open the file, then you read from the file, finally you close the file.

$FileName = "data.txt"; $FilePointer = fopen ($FileName, "mode"); $Array = file ($FileName); fclose ($FilePointer);

The file() function is a valuable built-in tool in PHP. It reads everything from a file and places that information into an array, with each array element being delineated by a carriage return or new line. If data.txt contains two lines of information, each of which ends with a new line (see Figure 10.6, but do not be confused by the fact that each line appears to spill over onto a second line), the corresponding array will contain two elements. The first element will be equal to the first line of data.txt and the second element equal to the second line. Once the data is stored into an array, it can be easily manipulated or printed.

Now you'll use this knowledge to create a script that both collects URLs from a user as well as displays previously submitted URLsall in one page!

To read from a file:

  1. Create a new document in your text editor.

  2. Begin with the standard HTML header (Script 10.4):

    Script 10.4. The script is rendered easier to understand by creating four functions: one to read from the file, one to write to it, one to create a form, and one to handle the form. Thus, the main body of the page is a simple conditional with calls to the functions.

    <HTML><HEAD> <TITLE>Storing URLs in an External File</TITLE> </HEAD><BODY>

    Because this page will both act as the form itself and handle the results of the form, I'll write this script a little differently than I have heretofore, which is why I do not begin the page itself with the functions as I otherwise would.

  3. Open a PHP code section and duplicate the WriteToFile() function from HandleForm.php (Script 10.3).

    <?php function WriteToFile ($URL, $Description) { $TheFile = "data.txt"; $Open = fopen ($TheFile, "a"); if ($Open) { fwrite ($Open, "$URL\ t$Description\n"); fclose ($Open); $Worked = TRUE; } else { $Worked = FALSE; } return $Worked; } // End of WriteToFile Function.

    You shouldn't have had to change any of the lines hereone of the benefits of programming with functions!

  4. Create a new function that will retrieve data from the file.

    function ReadFromFile () { $TheFile = "data.txt"; $Open = fopen ($TheFile, "r"); if ($Open) { print ("URLs currently listed in the data file:<P>\n"); $Data = file ($TheFile); for ($n = 0; $n < count($Data); $n++) { $GetLine = explode("\t", $Data[$n]); print ("$GetLine[0]<BR> \n$GetLine[1]<P>\n"); } fclose ($Open); print ("<HR><P>\n"); } else { print ("Unable to read from data.txt! <BR>\n"); } } // End of ReadFromFile Function.

    This function begins like WriteToFile() with the identification of the file, the attempt to open it (using r as the mode so that the PHP can read the data), and then continues on, assuming it successfully opened the file.

    The function will then print a caption and read the file data into an array called $Data. Each element of $Data is a string (in the format of the URL, followed by a tab, followed by its description, followed by the new line). You'll turn each string into a new array, called $GetLine, by looping through $Data one element at a time. Within the loop, the explode() function will create that $GetLine from the string by separating out the elements based upon the location of the tab. Using this new variable, you can print the pieces of the original string individually.

    Finally, the file is closed, some HTML for- matting is sent to the browser, and then the conditional is completed, generating an error message if PHP cannot open the file.

  5. Now write a third function, which will create the HTML submission form with each call.

    function CreateForm () { print ("Add a URL to the data file:\n"); print ("<FORM ACTION=\"urls.php\" METHOD=POST>\n"); print ("URL <INPUT TYPE=TEXT NAME= \"Array[URL]\" SIZE=60><BR>\n"); print ("Description <TEXTAREA NAME=\"Array[Description]\" ROWS=5 COLS=40></TEXTAREA> <BR>\n"); print ("<INPUT TYPE=HIDDEN NAME= \"BeenSubmitted\" VALUE= \"TRUE\">\n"); print ("<INPUT TYPE=SUBMIT NAME= \"SUBMIT\" VALUE=\"Submit!\"> </FORM>\n"); } // End of the CreateForm function.

    This function is mostly just the form.html page with two major changes. First, the form's ACTION tag now sends the form data to urls.php, which will be the name of this script. Second, I have added a hidden field which sets the value of $BeenSubmitted to TRUE. You'll see why I do this shortly.

  6. Write a fourth function for the purposes of handling the form.

    function HandleForm () { global $Array;

    This function is based upon the previous HandleForm.php script. The first thing it will do is bring in the $Array variable, by using the global statement, which holds the form data.

  7. The bulk of this function is from the main body of the previous HandleForm.php page (Script 10.4).

    $Pattern = "(http://)? ([^[:space:]]+)([[:alnum:] \.,-_?/&=])"; if (eregi($Pattern, $Array ["URL"])) { $Replace = "<a href=\"http:// \2\3\" target=\"_new\"> \2\3</a>"; $Array["URL"] = eregi_replace($Pattern, $Replace, $Array["URL"]); $CallFunction = WriteToFile ($Array["URL"], $Array["Description"]); if ($CallFunction) { print ("Your submission $Array[URL]has been received!<P><HR><P> \n"); } else { print ("Your submission was not processed due to a system error! <BR>\n"); } } else { print ("Please enter a valid Web address!\n"); } } // End of the HandleForm function.

    The function goes through the regular expression processes and will print out an error message if an invalid URL is entered. Assuming a valid URL has been submitted, the $CallFunction line and its corresponding conditional comes next .

  8. Finally, create the conditional that decides whether or not to handle the form.

    if ($BeenSubmitted){ HandleForm(); } ReadFromFile(); CreateForm();

    If the value of $BeenSubmitted is TRUE (which means that the form has been submitted), the data will be processed. If the value of $BeenSubmitted is FALSE, which means the user has not submitted anything, then the HandleForm() function is not called. In either case, the existing data is displayed from the file and then a form is created so that the user may enter another URL.

  9. Close the PHP and HTML.

    ?></BODY></HTML>

  10. Save the page as urls.php, upload it to the server, and test it in your Web browser (Figures 10.7, 10.8, and 10.9).

    Figure 10.7. The first time the user comes to the page, $BeenSubmitted is not equal to TRUE, so HandleForm() is never called (see Script 10.4). Once the form has been submitted, the PHP will handle the results and print a response as in Figure 10.8.

    Figure 10.8. After the user submits the form, urls.php will first handle the data then display the information from the file and create a new form.

    Figure 10.9. This is the source of urls.php, after the form has been submitted. Notice that all URLs are made clickable and that the form uses a hidden value, which the user is oblivious to, that adds functionality to the design.

I l @ ve RuBoard

Категории