File Write

☰ Menu Content


Lets get on to the most useful part of file manipulation, writing.

The function used to write is called fwrite.

File Open: Write

Before we can write to a file we have to open the file using fopen function.

PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myfile, 'w');

File Write: fwrite Function

The fwrite function allows data to be written to any type of file.

Fwrite's first parameter is the file handle and its second parameter is the string of data that is to be written.

Below we are writing a couple of names into our test file testFile.txt and separating them with a carriaged return.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");

$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);

$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);

The $fh variable contains the file handle for testFile.txt.

The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.

We wrote to the file testFile.txt twice.

Each time we wrote to the file we sent the string $stringData that first contained Bobby Bopper and second contained Tracy Tanner.

After we finished writing we closed the file using the fclose function.

If you were to open the testFile.txt file in NOTEPAD it would look like this:

Contents of the testFile.txt File:
Bobby Bopper
Tracy Tanner

File Write: Overwriting

When you open an existing file for writing with function fopen all the data contained in the file is wiped clean and you start with an empty file.

In the example bel;ow we open an existing file and write some new data into it.

PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");

$stringData = "Floppy Jalopy\n";
fwrite($fh, $stringData);

$stringData = "Pointy Pinto\n";
fwrite($fh, $stringData);
fclose($fh);

If you now open the testFile.txt file you will see that Bobby and Tracy have both vanished, as we expected, and only the data we just wrote is present.

Contents of the testFile.txt File:
Floppy Jalopy
Pointy Pinto

Note
For more detail please see Php Manual at http://www.php.net

Php Tutorial Content (menu)