Team LiB
Previous Section Next Section

Working with fopen() and fclose()

Before you jump headfirst into working with files, you need to learn a bit about the fopen() function, which is used to open files. This function requires a filename and mode, and it returns a file pointer. The file pointer provides information about the file and is used as a reference.

The filename is the full path to the file you want to create or open, and the mode can be any of the modes listed in Table 9.1.

Table 9.1: Modes Used with fopen()

Mode

Usage

r

Opens an existing file and reads data from it. The file pointer is placed at the beginning of the file.

r+

Opens an existing file for reading or writing. The file pointer is placed at the beginning of the file.

w

Opens a file for writing. If a file with that name does not exist, the function creates a new file. If the file exists, the function deletes all existing contents and places the file pointer at the beginning of the file.

w+

Opens a file for reading and writing. If a file with that name does not exist, the function creates a new file. If the file exists, the function deletes all existing content and places the file pointer at the beginning of the file.

a

Opens a file for writing. If a file with that name does not exist, the function creates a new file. If the file exists, the function places the file pointer at the end of the file.

a+

Opens a file for reading and writing. If a file with that name does not exist, the function attempts to create a new file. If the file exists, the function places the file pointer at the end of the file.

Creating a New File

Compared to the first section of this chapter, this next task is a piece of cake. The goal is simply to create a new, empty file in a specified location.

  1. Open a new file in your text editor and start a PHP block:

    <?
    
  2. Create a variable to hold the full path name to a file:

    $filename = "/Documents and Settings/Owner/Desktop/misc/mydata.txt";
    
    
    Note 

    This directory is one that exists on my own machine. Substitute your own directory name so that this works for you!

  3. Create a file pointer and use the fopen() function to open the file specified in step 3 for reading and writing. The die() function will cause the script to end and a message to be displayed if the file doesn't open properly.

    $newfile = fopen($filename, "w+") or die("Couldn't create file.");
    
    
    Note 

    The term file pointer is used to refer to the just-opened file.

  4. Close the file pointer:

    fclose($newfile);
    
  5. Create a message to print upon success, and then close your PHP block:

    $msg = "<P>File created!</P>";
    ?>
    
  6. Add this HTML:

    <HTML>
    <HEAD>
    <TITLE>Creating a New File</TITLE>
    </HEAD>
    <BODY>
    
    
  7. Print the message:

    <? echo "$msg"; ?>
    
  8. Add some more HTML so that the document is valid:

    </BODY>
    </HTML>
    
  9. Save the file with the name newfile.php, and place this file in the document root of your web server.

  10. Open your web browser and type http://127.0.0.1/newfile.php.

If the file creation was successful, you should see the success message shown in the following figure.

Click To expand

However, if your file creation failed, you will see a nasty parse error. You can force an error by using an invalid value for $filename, such as this:

$filename =
"/bozo/mydata.txt";

When you run your script, you'll see something like the following figure.

Click To expand

Although the die() function will do its job by printing the specified error message, PHP will issue its own warnings based on the failure of the function to do its job. You can suppress errors and warnings from PHP by using the @ sign in front of functions.

In your script, change this line

$newfile = fopen($filename,
"w+") or die("Couldn't create
file.");

to this:

$newfile = @fopen($filename,
"w+") or die("Couldn't create
file.");
Click To expand

Save the file and access the script via your web browser. You'll now see just the message from the die() function, and no other warnings.

Checking if a File Already Exists

To avoid any possible housekeeping errors when running around your file system, you can use the file_exists() function to check if a file already exists before you create it. This next script will do just that, and will print a message one way or the other.

  1. Open a new file in your text editor and start a PHP block:

    <?
    
  2. Create a variable to hold the full path name to a file (use your own file path):

    $filename = "/Documents and Settings/Owner/Desktop/misc/mydata.txt";
    
    
    Note 

    Yes, this is the same file you probably created in the previous section. That's fine, because it can trip the error checking!

  3. Start an ifelse statement that checks for a true/false result to the file_exists() function:

    if (file_exists($filename)) {
    
  4. Create a variable to hold a message regarding the file's existence:

    $msg = "<P>File already exists.</P>";
    
  5. Continue the else statement to do something if the file doesn't exist:

    } else {
    
  6. Create a file pointer and use the fopen() function to open the file specified in step 2 for reading and writing. The die() function will cause the script to end and a message to be displayed if the file doesn't open properly.

    $newfile = @fopen($filename, "w+") or die("Couldn't create file.");
    
  7. Create a variable to hold a success message:

    $msg = "<P>File created!</P>";
    
    
  8. Close the file pointer, the ifelse statement, and your PHP block:

    fclose($newfile);
    }
    ?>
    
  9. Add this HTML:

    <HTML>
    <HEAD>
    <TITLE>Creating a New File</TITLE>
    </HEAD>
    <BODY>
    
  10. Print the message:

    <? echo "$msg"; ?>
    
  11. Add some more HTML so that the document is valid:

    </BODY>
    </HTML>
    
  12. Save the file with the name newfile-checkfirst.php, and place this file in the document root of your web server.

  13. Open your web browser and type http://127.0.0.1/newfile-checkfirst.php.

Assuming that you used the filename of a previously created file, you should see the failure message shown in the next figure.

Click To expand

If you change the value of $filename to a file that doesn't exist and then access the script again, you'll see the success message. Because just creating a file is boring, in the next section you learn how to write data to the file.

Appending Data to a File

The goal of the next script is to append data to a file. If the file exists, the script will just write data into it. If the file doesn't exist, it will be created before data is written to it.

  1. Open a new file in your text editor and start a PHP block:

    <?
    
  2. Create a variable to hold the full path name to a file (use your own file path):

    $filename = "/Documents and Settings/Owner/Desktop/misc/textfile.txt";
    
    
  3. Create a variable called $newstring to hold the string you want to write to the file. Populate that string with this very exciting message:

    Click To expand
  4. Create a file pointer and use the fopen() function to open the file specified in step 2 for reading and writing. The die() function will cause the script to end and a message to be displayed if the file doesn't open properly.

    $myfile = @fopen($filename, "w+") or die("Couldn't open file.");
    
  5. Use the fwrite() function to place the text ($newstring) inside the file ($myfile). The die() function will cause the script to end and a message to be displayed if the fwrite() function fails.

    @fwrite($myfile, $newstring) or die("Couldn't write to file.");
    
  6. Create a variable to hold a success message:

    $msg = "<P>File has data in it now...</p>";
    
  7. Close the file pointer and the PHP block:

    fclose($myfile);
    ?>
    
  8. Add this HTML:

    <HTML>
    <HEAD>
    <TITLE>Adding Data to a File</TITLE>
    </HEAD>
    <BODY>
    
    
  9. Print the message:

    <? echo "$msg"; ?>
    
  10. Add some more HTML so that the document is valid:

    </BODY>
    </HTML>
    
  11. Save the file with the name writedata.php, and place this file in the document root of your web server.

  12. Open your web browser and type http://127.0.0.1/writedata.php.

    Click To expand

In the next section, you read the data from the text file created by this script.

Reading Data From a File

You'll now create a script to read the data from the file you created in the previous section. You could just open that file in a text editor, but where's the fun in that? PHP has a handy function called fread() that does the job for you.

  1. Open a new file in your text editor and start a PHP block:

    <?
    
  2. Create a variable to hold the full path name to the file you created in the previous section (use your own path):

    $filename = "/Documents and Settings/Owner/Desktop/misc/textfile.txt";
    
  3. Create a file pointer and use the fopen() function to open the file specified in step 2 for reading only. The die() function will cause the script to end and a message to be displayed if the file doesn't open properly.

    $whattoread = @fopen($filename, "r") or die("Couldn't open file");
    
  4. Create a variable called $file_contents, and use the fread() function to read all the lines from the open file pointer ($whattoread) for as long as there are lines in the file:

    Click To expand
  5. Create a variable to print a message, including the contents of the file:

    $msg = "The file contains:<br>$file_contents";
    
  6. Close the file pointer and your PHP block:

    fclose($whattoread);
    ?>
    
  7. Add this HTML:

    <HTML>
    <HEAD>
    <TITLE>Reading Data From a File</TITLE>
    </HEAD>
    <BODY>
    
    
  8. Print the message:

    <? echo "$msg"; ?>
    
  9. Add some more HTML so that the document is valid:

    </BODY>
    </HTML>
    
  10. Save the file with the name readdata.php, and place this file in the document root of your web server.

  11. Open your web browser and type http://127.0.0.1/readdata.php.

    Click To expand

That's definitely the string written to the file, but what happened to that line break? The newline character means nothing to a web browser, which renders only HTML. Luckily, the PHP development team had great forethought and created the nl2br() function (newline-to-break; get it?). Make some slight adjustments to the readdata.php script:

  1. Add this line after the line containing the fread() function:

    $new_file_contents =
    nl2br($file_contents);
    
  2. Modify the $msg string so that it looks like this:

    $msg = "The file contains:<br>$new_file_contents";
    
  3. Save the file.

Now open this file in your web browser, and notice the line break, as shown here.

Click To expand

In the next section, you read the same message, but instead of printing it on the screen, you send it via e-mail.

Sending File Contents via E-Mail

If you're saving the results of HTML forms to a plain text file, which you want to read only at specific times, you can write a little script that mails the contents of the file to you on demand.

  1. Open a new file in your text editor and start a PHP block:

    <?
    
  2. Create a variable to hold the full path name to the file containing the data (use your own path):

    $filename = "/Documents and Settings/Owner/Desktop/misc/textfile.txt";
    
  3. Create a file pointer and use the fopen() function to open the file specified in step 2 for reading only. The die() function will cause the script to end and a message to be displayed if the file doesn't open properly.

    $whattoread = @fopen($filename, "r") or die("Couldn't open file");
    
    
  4. Create a variable called $file_contents, and use the fread() function to read all the lines from the open file pointer ($whattoread) for as long as there are lines in the file:

    $file_contents = fread($whattoread, filesize($filename));
    
  5. Create a variable to hold your e-mail address:

    $to = "you@yourdomain.com";
    
  6. Create a variable for the subject of the e-mail:

    $subject = "File Contents";
    
  7. Create a variable for additional mail headers:

    $mailheaders = "From: My Web Site <genericaddress@yourdomain.com> \n";
    
  8. Populate the mail() function using the $file_contents string as the third argument (the message):

    mail($to, $subject, $file_contents, $mailheaders);
    
  9. Create a variable to print a message to the screen:

    $msg = "<P>Check your mail!</P>";
    
  10. Close the file pointer and your PHP block:

    fclose($whattoread);
    ?>
    
  11. Add this HTML:

    <HTML>
    <HEAD>
    <TITLE>Mailing Data From a File</TITLE>
    </HEAD>
    <BODY>
    
  12. Print the message:

    <? echo "$msg"; ?>
    
    
  13. Add some more HTML so that the document is valid:

    </BODY>
    </HTML>
    
  14. Save the file with the name mailcontents.php, and place this file in the document root of your web server.

  15. Open your web browser and type http://127.0.0.1/mailcontents.php.

Like the message says, go check your mail! You should have an e-mail waiting for you, with the contents of the file printed in it.

Click To expand

Unlike with the previous script, you didn't need to use the nl2br() function, because you weren't displaying text in a web browser window. The plain-text e-mail will keep the original line break.


Team LiB
Previous Section Next Section