File I/O in PHP

Because of the history of PHP, file functions, just like string functions, were mostly influenced by the C standard library functions and have very similar naming and usage. Writing binary or plaintext data is determined by which functions you use. In general whether or not a file input/output stream is buffered or unbuffered is determined by the system configuration. There are some ways in which this can be changed, but we will not cover them in detail.

Opening Files

Files are represented in PHP as a “resource” (also referred to as a handle) that can be passed around to other functions to read and write to the file. For our purposes, a resource is simply a variable that can be stored and passed to other functions. To open a file, you use the fopen() function (short for file open) which requires two arguments and returns a file handle. The first argument is the file path/name that you want to open for processing. The second argument is a string representing the “mode” that you want to open the file in. There are several supported modes, but the two we will be interested in are reading, in which case you pass it "r" and writing in which case you pass it "w". The path can be an absolute path, relative path, or may be omitted if the file is in the current working directory.

The two conditionals above check that the file opened successfully. If opening the file failed, fopen() returns false (and the interpreter issues warning).

When a file is opened, the file handle returned by fopen() initially points to the beginning of the file. As you read or write from it, the resource advances through the file content.

Reading and Writing Files

Reading files in PHP

There are a couple of ways to read input from a file. To read a file line by line, we can use fgets() to get each line. It takes a single argument: the file handle that was returned by fopen() and returns a string containing the entire line including the endline character. If necessary, leading and trailing whitespace can be removed using trim() . To determine the end of a file you can use feof() which returns true when the handle has reached the end of the file. Code Sample below contains a full example of processing a file line-by-line:

//open a file for reading (input):
$input = fopen("/user/apps/data.txt", "r");
//open a file for writing (output):
$output = fopen("./results.txt", "w");

if(!$input) {
    printf("Unable to open input file\n");
    exit(1);
}

if(!$output) {
    printf("Unable to open output file\n");
    exit(1);
}

$h = fopen("input.data", "r");
while(!feof($h)) {
    //read the next line:
    $line = fgets($h);
    //trim it:
    $line = trim($line);
    //process it, we'll just print it
    print $line;
}

Alternatively there is a convenient function, file_get_contents() that will retrieve the entire file as a string: $fileContents = file_get_contents("./inputFile.txt");

Writing files in PHP

There are several ways that we can output to files, but the easiest is to simply use fwrite() (short for file write). This is a “binary-safe” file output function that takes two arguments: the file handle to write to and a string of data to be written. It also returns an integer representing the number of bytes written to the file (or false on error).

$x = 10;
$y = 3.14;

//write to a plaintext file
fwrite($output, "Hello World!\n");
fwrite($output, "x = $x, y = $y\n");

Using URLs

A nice feature of PHP is that you can use URLs as file names to read and write to a URL. “Reading” from a URL mean connecting to a remote resource, such as a webservice and downloading its contents (which may be HTML, XML or JSON data). Writing to a URL may be used to post data to a web page in order to receive a response. As an example, we can download a webpage in PHP as follows:

$h = fopen("http://cse.unl.edu", "r");
$contents = "";
while(!feof($h)) {
$contents .= fgets($h);
}

//or just:
$contents = file_get_contents("http://cse.unl.edu");

Closing Files

Once you are done processing a file, you should close it using the fclose() function.

fclose($h);

which takes a single argument, the file handle that you wish to close.


Licenses and Attributions


Speak Your Mind

-->