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.
|
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. |
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.
Open a new file in your text editor and start a PHP block:
<?
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! |
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. |
Close the file pointer:
fclose($newfile);
Create a message to print upon success, and then close your PHP block:
$msg = "<P>File created!</P>"; ?>
Add this HTML:
Print the message:
<? echo "$msg"; ?>
Add some more HTML so that the document is valid:
</BODY> </HTML>
Save the file with the name newfile.php, and place this file in the document root of your web server.
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.
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.
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.");
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.
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.
Open a new file in your text editor and start a PHP block:
<?
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! |
Start an if…else statement that checks for a true/false result to the file_exists() function:
if (file_exists($filename)) {
Create a variable to hold a message regarding the file's existence:
$msg = "<P>File already exists.</P>";
Continue the else statement to do something if the file doesn't exist:
} else {
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.");
Create a variable to hold a success message:
Close the file pointer, the if…else statement, and your PHP block:
fclose($newfile); } ?>
Add this HTML:
<HTML> <HEAD> <TITLE>Creating a New File</TITLE> </HEAD> <BODY>
Print the message:
<? echo "$msg"; ?>
Add some more HTML so that the document is valid:
</BODY> </HTML>
Save the file with the name newfile-checkfirst.php, and place this file in the document root of your web server.
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.
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.
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.
Open a new file in your text editor and start a PHP block:
<?
Create a variable to hold the full path name to a file (use your own file path):
Create a variable called $newstring to hold the string you want to write to the file. Populate that string with this very exciting message:
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.");
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.");
Create a variable to hold a success message:
$msg = "<P>File has data in it now...</p>";
Close the file pointer and the PHP block:
fclose($myfile); ?>
Add this HTML:
Print the message:
<? echo "$msg"; ?>
Add some more HTML so that the document is valid:
</BODY> </HTML>
Save the file with the name writedata.php, and place this file in the document root of your web server.
Open your web browser and type http://127.0.0.1/writedata.php.
In the next section, you read the data from the text file created by this script.
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.
Open a new file in your text editor and start a PHP block:
<?
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";
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");
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:
Create a variable to print a message, including the contents of the file:
$msg = "The file contains:<br>$file_contents";
Close the file pointer and your PHP block:
fclose($whattoread); ?>
Add this HTML:
Print the message:
<? echo "$msg"; ?>
Add some more HTML so that the document is valid:
</BODY> </HTML>
Save the file with the name readdata.php, and place this file in the document root of your web server.
Open your web browser and type http://127.0.0.1/readdata.php.
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:
Add this line after the line containing the fread() function:
$new_file_contents = nl2br($file_contents);
Modify the $msg string so that it looks like this:
$msg = "The file contains:<br>$new_file_contents";
Save the file.
Now open this file in your web browser, and notice the line break, as shown here.
In the next section, you read the same message, but instead of printing it on the screen, you send it 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.
Open a new file in your text editor and start a PHP block:
<?
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";
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.
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));
Create a variable to hold your e-mail address:
$to = "you@yourdomain.com";
Create a variable for the subject of the e-mail:
$subject = "File Contents";
Create a variable for additional mail headers:
$mailheaders = "From: My Web Site <genericaddress@yourdomain.com> \n";
Populate the mail() function using the $file_contents string as the third argument (the message):
mail($to, $subject, $file_contents, $mailheaders);
Create a variable to print a message to the screen:
$msg = "<P>Check your mail!</P>";
Close the file pointer and your PHP block:
fclose($whattoread); ?>
Add this HTML:
<HTML> <HEAD> <TITLE>Mailing Data From a File</TITLE> </HEAD> <BODY>
Print the message:
Add some more HTML so that the document is valid:
</BODY> </HTML>
Save the file with the name mailcontents.php, and place this file in the document root of your web server.
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.
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.