File Handling in PHP

By: Andi, Stig and Derick Viewed: 153176 times    

Let’s begin with the basic file-accessing functions. Originally, those functions only worked on normal files, so their names begin with “f,” but PHP extends this to almost everything. The most used functions for file access afopen() Opens a handle to a local file, or a file from an URL

  • fread() Reads a block of data from a file

  • fgets() Reads one single line from a file

  • fwrite() / fputs() Writes a block of data to a file

  • fclose() Closes the opened file handle

  • feof() Returns true when the end of the file has been reached

Working with files is easy, as the following example shows:

<?php

/* Open a file */

$fp = fopen ('data.dat', 'r');

if (!$fp) {

die ("The file could not be opened.");

}

/* Read a line from the file */

$line = fgets($fp);

/* Close the file handle */

fclose($fp);

?>

In line 3, a file handle ($fp) is associated with the stream and the stream is associated with the counter.dat file that is on disk. The first parameter is the path to the file. The second parameter passed to fopen() is the mode. The mode specifies whether a stream is opened for reading, writing, both reading and writing, or appending. The following modes exist:

  • r Opens the stream in read-only mode. The file pointer is placed at the beginning of the stream.

  • r+ Opens the stream for reading and writing. The file pointer is placed at the beginning of the stream.

  • w Opens the stream in write-only mode. The file is cleared and the file pointer is placed at the beginning of the stream. If the file does not exist, an attempt is made to create the file.

  • w+ Opens the stream for reading and writing. The file is cleared and the file pointer is placed at the beginning of the stream. If the file does not exist, an attempt is made to create the file.

  • a Opens in write-only mode. The file pointer is placed at the end of the stream. If the file does not exist, an attempt is made to create the file.

  • a+ Opens for reading and writing. The file pointer is placed at the end of stream. If the file does not exist, an attempt is made to create it.

 

The b modifier can be used with the mode to specify that the file is binary. Windows systems differentiate between text and binary files; if you don’t use the b modifier for binary files in Windows, your file may become corrupted. Consequently, to make your scripts portable to Windows, it’s wise to always use the b modifier when you work on a binary file, even when you are developing code on an operating system that doesn’t require it. On UNIX OSs (Linux, FreeBSD, MacOSX, and so on), the b modifier has no effect whatsoever.

Here’s another small example:

<?php

/* Open a file in read/write mode and binary mode, and place

* the stream pointer at the beginning of the stream. */

$fp = fopen("/tmp/tempfile", "rb+");

/* Try to read a block of 4096 bytes from the file */

$block = fread($fp, 4096);

/* Write that same block of data to the stream again

* just after the first one */

fwrite($fp, $block);

/* Close the stream */

fclose($fp);

?>

A third optional parameter, true, is available for fopen() that tells PHP to look in your include path for the file. The following script first tries to open php.ini (in read-only mode) from /etc , then from /usr/local/etc , and finally from the current directory (the dot in the path specifies the current directory). Because php.ini is not a binary file, we do not use the b modifier for the mode:

<?php

/* Set the include path */

ini_set('include_path', '/etc:/usr/local/etc:.');

/* Open handle to file */

$fp = fopen('php.ini', 'r', TRUE);

/* Read all lines and print them */

while (!feof($fp)) {

$line = trim(fgets($fp, 256));

echo ">$line<\n";

}

/* Close the stream handle */

fclose($fp);

?>

This script uses feof() , which is a function we haven’t seen before. feof() tests whether the end of a file has been reached during the last fread() or fgets() call. We use fgets() here, with 256 as  the second parameter. This number specifies the maximum length if the line that fgets() reads. It is important to choose this size carefully. PHP allocates this memory before reading, so if you use a value of 1,000,000, PHP allocates 1MB of memory, even if your line is only 12 characters long. The default is 1,024 bytes, which should be enough for almost all appliances.

Try to decide whether you really need to load the entire file into memory when processing a file. Suppose you need to scan a text file for occurrences of a defined phrase with a regular expression. If you load the file into memory with the file_get_contents() function and then run the preg_match_all() function, you actively waste many resources. It would be more efficient to use a while

(!feof($fp)) { $line = fgets($fp); }

loop, which doesn’t waste memory by loading the entire file into memory. It would speed up the regular expression matching as well.

Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial