Larger Text
Normal Text
Smaller Text
IT 280 Web Development II, Spring 2008
Using files with PHP
- Many Web applications need to save data submitted by the user.
- Often this is achieved by interfacing with a database system which manages the storage and retrieval of data.
- Some smaller applications may make use of simple text files for storage.
- We have already used text files to store information that is incorporated into a document with the
include() function.
- However the files were created using an editor, with content decided by the writer, not with data from the user.
- Now we will see how to write into a text file from within a PHP program.
Ways of using a file
- PHP has seven different ways of working with a file. We will look at just two of them.
- You can replace all the text in a file with new text, overwriting any that is already there. This is called write-only mode.
- You can add new text to to the end of the file without erasing what is already there. This is called append mode.
Starting work with a file: the fopen() function
- The
fopen() function tells PHP the name of the file to be used and the mode.
- It returns a filehandle that you use in later statements when you use the file.
- The first argument is the filename.
- It can be a string literal or a variable.
- If the data file is not in the same directory as the PHP file, the name must include the path to it.
- The second argument is the mode. 'w' for write, or 'a' for append.
Example
$myHandle = fopen($filename, 'w'); // opens in write mode
$myHandle = fopen($filename, 'a'); // opens in append mode
A limitation
- In both modes, the HTTP server must have permission to write to the file.
- Normally it will not be permitted to.
- This occurs because the web server and your file have different owners.
- To permit the web server to write to your file, you must give the file "other write" permission.
- You can do this by setting the file properties through the Secure File Transfer window or with the Unix command "chmod 646 filename".
Creating new files
- Similarly, if the file does not yet exist, PHP will try to create it.
- Normally it will not be permitted to, because it does not have permission to create new files in your directory.
- Thus any file you open for writing or appending must already exist and must have the necessary permissions (646).
- If necessary, you can use Pico to create a file with a blank line it.
Getting text into a file: the fwrite() function
- To write text into a file, in both modes, you use the
fwrite() function.
- It has two arguments.
- The first is the file to be used (the filehandle from the
fopen).
- The second is the text to be written (a string literal or variable).
Example
fwrite($myHandle, "this is some text to be written into the file");
Finishing up: the fclose() function
- When you are finished writing text into a file, it should be closed with the
fclose() function.
- The argument is the filehandle.
fclose($myHandle);
Example 1
- This PHP program writes two lines into the file named testfile.txt.
- The mode is "w"
- On wyrd, the file must exist; it cannot be created by PHP.
- Any text that is already in the file will be overwritten.
<?php
//file firstwrite.php
$myHandle = fopen('testfile.txt', 'w'); //Open in write mode
fwrite($myHandle, "Line of text to be written into the file.\n");
fwrite($myHandle, "A second line of text.\n");
fclose($myHandle);
?>
<body>
<h1>Writing done.</h1>
</body>
Here is the first example.
Example 2
- This PHP program adds two lines to the file named testfile2.txt.
- The mode is "a"
- On wyrd, the file must exist; it cannot be created by PHP.
- The new text will be added to what is already there.
<?php
//file secondwrite.php
$myHandle = fopen('testfile2.txt', 'a'); //Open in write mode
fwrite($myHandle, "Another line of text to be written into the file.\n");
fwrite($myHandle, "yet another line of text.\n");
fclose($myHandle);
?>
<body>
<h1>Appending done.</h1>
</body>
Here is the second example.
Safety first - the strip_tags() function
- If a web page gets data from the user and writes it into a file, it is a potential security problem.
- A malicious user might be able to
- insert commands in the text that may subsequently get executed.
- insert tags or scripts that mess up the page at the next stage
- insert tags or scripts that create problems for the next user.
- it is wise to remove all HTML tags from user-supplied data.
- The
strip_tags() function strips all HTML tags from its argument.
- It returns the cleaned-up string.
Example3
For example, the output of
$clean = strip_tags("<p>Hello</p><?php echo 'whatever' ?>");
echo $clean;
is just
Hello
Here is the third example.
Important Security Precaution
- Stripping tags from user-supplied data is an important security precaution, especially if the data are written to a file.
- Any PHP script you write must take this precaution.
Writing form data to a file
- Writing data from a form into a file is the same as writing a literal.
- You just use $_GET[] or $_POST[].
Example application: A logbook.
We now have all the tools needed to make a basic logbook or guestbook.
- Form has inputs for the user's name and comments.
- New entry is typed into a form.
- Form is submitted.
- Entries are retrieved using $_POST[]
- Entries are cleaned up using strip_tags()
$safe_email = strip_tags($_POST['username']);
$safe_comments = strip_tags($_POST['comments']);
- Add some HTML around the data.
$record = $safe_comments
."<br />\n-- "
.$safe_email
."<hr />\n\n";
- Open the file with mode "a" and append the new lines.
$loghandle = fopen("logdata.txt", 'a');
fwrite($loghandle, $record);
fclose($loghandle);
- To see the entries - just use the include() function!
<h2>Previous entries</h2>
<?php include("logdata.txt"); ?>
The Example.
Getting text out of a file: the file_get_contents() function
Sometime you need to retrieve the contents of a file for use in a program. The file_get_contents() returns the contents of a text file as a string. there is no need to open or close the file in separate steps.
The next example is a variation on the logbook. However new entries are inserted at the top rather than at the end. To achieve this, the program uses the following steps.
- get the previous messages from the file (file_get_contents)
- prepare the file for writing(fopen)
- write the new entry into the (now empty) file
- write the previous messages back into the file
Example variation: newest messages first.
Example logbook2.