Saturday, April 4, 2009

Working with Files in PHP

Reading a file with fopen()

Basic example for reading a file is as

<?php
// store the pathname of the file
$filename = 'C:/testfolder/filetest.txt';
// open the file in read-only mode
$file = fopen($filename, 'r');
// read the file and store its contents
$contents = fread($file, filesize($filename));
// close the file
fclose($file);
// display the contents
echo nl2br($contents);
?>

process. Unlike file_get_contents(), the function fread() needs to know how much of the file to read. So you need to supply a second argument indicating the number of bytes. This can be useful if you want, say, only the first 100 characters of a text file. However, if you want the whole file, you need to pass the file’s pathname to filesize() to get the correct figure.

The nl2br() function in the final line converts new line characters to XHTML
tags.

Other way of reading the File is

$contents = fread($file, filesize($filename));
with this (the full script is in fopen_readloop.php)
// create variable to store the contents
$contents = '';
// loop through each line until end of file
while (!feof($file)) {
// retrieve next line, and add to $contents
$contents .= fgets($file);
}

fgets() function retrieves one line at a time

Replacing content with fopen()

The first of the write-only modes (w) deletes any existing content in a file, so it’s useful for working with files that need to be updated frequently. You can test the w mode with fopen_write.php, which has the following PHP code above the DOCTYPE declaration:

<?php
// if the form has been submitted, process the input text
if (array_key_exists('putContents', $_POST)) {
// strip backslashes from the input text and save to shorter variable
$contents = get_magic_quotes_gpc() ?
stripslashes($_POST['contents']) : $_POST['contents'];
// open the file in write-only mode
$file = fopen('C:/testfolder/filetest04.txt', 'w');
// write the contents
fwrite($file, $contents);
// close the file
fclose($file);
}
?>

There’s no need to use a loop this time: you’re just writing the value of $contents to the opened file. The function fwrite() takes two arguments: the reference to the file and whatever you want to write to it.

Appending content with fopen()

The append mode is one of the most useful ways of using fopen(), because it adds new
content at the end, preserving any existing content. The main code in fopen_append.php is the same as fopen_write.php, apart from those elements highlighted here in bold:

// open the file in append mode
$file = fopen('C:/testfolder/filetest.txt', 'a');
// write the contents after inserting new line
fwrite($file, "\r\n$contents");
// close the file
fclose($file);

If this file is loaded into a browser and insert some text, it should now be added
to the end of the existing text.

Notice that I have enclosed $contents in double quotes and preceded it by carriage return and new line characters (\r\n). This makes sure that the new content
is added on a fresh line. When using this on Mac OS X or a Linux server, omit the carriage return, and use this instead:

fwrite($file, "\n$contents");

Writing a new file with fopen()
Although it can be useful to have a file created automatically with the same name, it may be exactly the opposite of what you want. To make sure you’re not overwriting an existing file, you can use fopen() with x mode. The main code in fopen_exclusive.php looks like this (changes are highlighted in bold):

// create a file ready for writing only if it doesn't already exist
$file = fopen('C:/testfolder/filetest01.txt', 'x');
// write the contents
fwrite($file, $contents);
// close the file
fclose($file);

If you try it more than once, you should get a series of error messages telling you that the file already exists.

Combined read/write operations with fopen()

By adding a plus sign (+) after any of the previous modes, the file is opened for both reading and writing. You can perform as many read or write operations as you like—and in any order—until the file is closed. The difference between the combined modes is as follows:

r+: The file must already exist; a new one will not be automatically created. The internal pointer is placed at the beginning, ready for reading existing content.

w+: Existing content is deleted, so there is nothing to read when the file is first opened.

a+: The file is opened with the internal pointer at the end, ready to append new material, so the pointer needs to be moved back before anything can be read.

x+: Always creates a new file, so there’s nothing to read when the file is first opened.

0 comments:

Post a Comment