PHP – Working with Files

Although I don't get much chance to write to files directly, since most of my work is with databases, every once in awhile its nice to know how to do this.

Working with files is much like working with a database, you first have to open a connection to the file, then, like with a database, you can: create a new file, read the file, and update the file. After you're done with the file operation, you close the file, just like you close a database. Let's see how we do this with PHP.

First, to open a file we use the fopen command like so:

$fileName = "testFile.txt";
$fileHandle = fopen($fileName,'a') or die("can't open file");

The fopen command generates a link to the file called, a file handle. We use the file handle for the rest of our file operations as a pointer to the file.

When you open a file, it is expected, that the programmer will know what he wants to do with the file. The fopen commands asks why the file is being openned. There are several choices to substitute for the 'a' in the fopen command:

'r'  Open for reading only; File pointer at the start of the file.

'r+' Open for reading and writing; File pointer at the start of the file.

'w'  Open for writing only; File pointer at the start of the file; Delete any contents. If the file does not exist, create it.

'w+'  Open for reading and writing; File pointer at the start of the file, Delete any contents. If the file does not exist, create it.

'a'   Open for writing only; File pointer at the end of the file. If the file does not exist, create it.

'a+'  Open for reading and writing; File pointer at the end of the file. If the file does not exist, create it.

'x'  Create and open for writing only; File pointer at the start of the file. If the file exists, generate an E_WARNING.

'x+'  Create and open for reading and writing; File pointer at the start of the file. If the file exists, generate an E_WARNING.

Quite an array of options. There are a few more, but these are the main choices. In reality, if you're adding to the contents of the file, like with a log or error file, you want to add the contents below anything else in the file, so the "a" is appropriate. If you're creating a new file, you would probably want to use the "w" or "x" to avoid overwriting an existing file. If you're just reading the file, a simple "r" will do.

Now that we have the file open, how do we add content and read the file.

$fileName = "testFile.txt";
$fileHandle = fopen($fileName, 'a') or die("can't open file");

$strTest = "The string to write to the file.";

// To write to the file
fwrite($fileHandle, $strTest);

// Close the file after the write
fclose($fileHandle);

The fwrite command says write the $strTest to the file. Since we openned the file to append, "a", $srtTest will be added to the end of any contents in the file.

How about reading, we could use fread() , like so:

$fileName = "testFile.txt";
$fileHandle = fopen($fileName, 'a') or die("can't open file");

// If we want to read the entire file
$lengthOfRead =  filesize($filename);

// You assign the output of the fread to a variable
$result = fgets($fileHandle, $lengthOfRead);

// If we want to read a line at a time
while (!feof($fileHandle))
{
	echo fgets($filehandle);
	// carriage return for a new line
  	echo "\t";
}

fclose($filehandle);

The $lengthOfRead variable is the amount of the file you want to read, in bytes. feof() tests for the end of the file. fgets() reads a line at a time.

Carriage returns at the end of the line are different for different operating systems. Use "\r" for the Mac, and "\n" for Linux, and Windows needs a "\r\n". In Windows, if you use a "\t" it will pick the right line ending for you.

There are few other commands in PHP that combine the fopen, fread or fwrite, and fclose all in one command, that I recommend.

file_puts_contents("testFile.txt", $strTest )

$fileContents = file_get_contents("testFile.txt");

file_puts_contents is identical to calling fopen(), fwrite() and fclose() successively to write data to a file. If the file exists the content will be overwritten. If the file doesn't exist it will be created.

file_gets_contents reads the entire file as a string to memory.

ANd there is one more way to read a file:

$fileContents = readfile("testFile.txt");

The main difference is that readfile writes its contents to the output buffer instead of memory. You can output it directly to your screen with a

print($fileContents).

As you can see, there's more than one way to accomplish the same task in PHP. You just need to know what you're trying to do, before you start doing it.

Comments are closed.