PHP for the World Wide Web (Visual QuickStart Guide)

I l @ ve RuBoard

Since you need to write something to a file in order to read something from it, we'll I'll explore writing first. Writing to a file on the server is a three-step process: first, you open the file; second, write your data to it; and, third, close the file. Fortunately PHP's built-in functions for doing these steps are quite obvious:

Table 10.1. Which mode to use when opening a file is rather self-evident. The most important things to keep in mind are: whether you will be reading, writing, or both, and what to do with any existing contents (append to or overwrite).

File Modes
Mode Allows For
r Read from the file only.
w Write to the file only, but it will create the file if it doesn't exist or discard existing contents before writing if the file does exist.
a Append new data to the end of the file and create the file if it doesn't exist.
r+ Read and write to the file.
w+ Read and write to the file, but it will create the file if it doesn't exist or discard existing contents before writing if the file does exist.
a+ Read from and write to the file and create the file if it doesn't exist. New data will be appended to the end of file.

$FileName = "data.txt"; $FilePointer = fopen ($FileName, "mode"); fwrite ($FilePointer, "data to be written"); fclose ($FilePointer);

When handling files, the first thing I do is assign the filename and path (where it is on the server) to a variable, for convenience sake. Use common path conventions when assigning the value (e.g., if the file was in the files directory which is a subset of the current directory, the filename would be files/data.txt ).

Once you've identified the file, you must create a file pointer when opening it. This file pointer, assigned to the appropriately-named $FilePointer variable, is used by PHP to refer to the open file.

The most important consideration when opening the file is what mode you use. Depending upon what you intend to do with the file, the mode dictates how to open it. The most forgiving mode is a+, which allows you to read or write to a file. It will create the file if it doesn't exist and it will appendhence a new data to the end of the file automatically. Conversely r will only allow you to read from a file. Table 10.1 lists all of the possible modes.

The fwrite() function will write the new data, sent as the second argument in the function call, to the file in accordance with the selected mode. Finally, you close the file by once again referring to the file pointer.

Let's create a form that stores user -submitted URLs in a separate file.

To write to an external file:

  1. If you wish, open form.html from Chapter 8, Regular Expressions , (Script 10.1) in your text editor.

    I'll make some minor changes to the form, but you can skip this step, if you wish, without affecting the end result.

    Script 10.1. This is the existing version of form.html. You can remove the first and last name lines, if you want to, as they won't be needed here (see Script 10.2).

  2. Remove the first and last name lines (Script 10.2).

    Script 10.2. In order to keep things orderly, I have cut out the unnecessary first and last name lines from form.html. However, since I did not alter the name of the two important inputsArray[URL] and Array[Description]leaving the page as it was would not be a problem either.

  3. Save your page and upload it to the server.

    Now you'll write a new HandleForm.php script to process the data generated by form.html.

  4. Create a new PHP document in your text editor.

  5. Begin by defining the PHP function (Script 10.3):

    Script 10.3. This script demonstrates a number of techniques learned to this point which you ought to consider using when programming. First, the function is written as the first element of the script. Second, the user-submitted data is checked for accuracy using regular expressions. Third, messages are sent to the browser in case of problems.

    <? function WriteToFile ($URL, $Description) {

    The WriteToFile() function takes two argumentsthe URL and the description of the URL which the user entered in form.html.

  6. Identify and open the file.

    $TheFile = "data.txt"; $Open = fopen ($TheFile, "a");

    These two lines identify the file and open it for writing only (creating, if necessary, and writing the new data to the end of the file if the file does exist). The data.txt file referred to here should be the same one that was created and had its proper permissions set in the previous section of this chapter.

  7. Now, you'll create a conditional based upon the success of the fopen() function.

    if ($Open) { fwrite ($Open, "$URL} t$Description\n");fclose ($Open); $Worked = TRUE; } else { $Worked = FALSE; }

    If the file is successfully opened, the function will then append the new data to the old. The format for the data is the URL followed by a tab character (created using an escaped t ), then the description followed by a new line character (created by an escaped n ). The file is then closed.

  8. Return the $Worked value and close the function.

    return $Worked; } // End of WriteToFile Function.

    If the file was successfully opened, the $Worked variable is set to TRUE and returned in order to indicate the success of the function.

    Figure .

  9. Close the initial PHP code and create the standard HTML header.

    ?> <HTML><HEAD><TITLE>Using Files </TITLE><BODY>

  10. Open the main PHP section.

    <?php

  11. Now define the regular expression pattern:

    $Pattern = "(http://)?([^[:space:]]+) ([[:alnum:]\.,-_?/&=])";

    Once again, regular expressions will be used to confirm a valid URL and then turn it into a clickable link.

  12. Create a conditional based upon successful execution of the regular expression.

    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 the user-submitted URL matches the regular expression, it will then be changed using eregi_replace() and the concept of back referencing. Then, the WriteToFile() function is called.

  13. Now, PHP will print a message based upon the results of the function call.

    if ($CallFunction) { print ("Your submission $Array[URL]has been received!<BR>\n"); } else { print ("Your submission was not processed due to a system error!<BR>\n"); }

    The $CallFunction variable will be equal to the returned value of $Worked from the function. If PHP could open the file, $Worked, and therefore $CallFunction will be TRUE, else it will be FALSE. Accordingly, a message will be displayed to the user indicating the result.

  14. Close the if statement, the PHP, and the HTML.

    } else { print ("Please enter a valid Web address!\n"); } ?> </BODY></HTML>

  15. Save your script as HandleForm.php, upload it to the server (in the same location as form.html and data.txt ), and test both in your Web browser (Figures 10.4,10.5,and 10.6).

    Figure 10.4. As long as the user enters a valid Web address and the script is able to write the data to the file, all the user should see is this.

    Figure 10.5. After running the form.html and HandleForm.php pages at least once, you can download data.txt to your computer and view it in your text editor. Notice that the HTML A HREF tag, generated with the eregi_replace() function, is written to the file as well.

    Figure 10.6. For each additional submission of form.html, another line of information will be added to data.txt. This particular text editor (BBEdit) also indicates tabs (with the triangle) and new lines (the last character on lines 2 and 4).

Tip

As an extra step of safe-checking, you can use the is_writeable() function to determine if the server will allow you to write data to the file before attempting to open it. Here is how you would begin to incorporate it (this is only the beginning of the script):

$TheFile = "data.txt"; if (is_writeable ($TheFile)) { $Open = fopen ($TheFile, "a");

Tip

On Windows servers, be sure to escape the backslashes in a filename path or use forward slashes instead. For example, you could say either c:\\php\\data.txt or c:/php/data.txt but not c:\php\data.txt since the backslash is the escape character. Unix servers use the forward slash as the standard so this is not an issue on those servers.

I l @ ve RuBoard

Категории