Writing to a file


In php we use the fwrite function to write data to a file, this takes 2 parameters. The first parameter is the file handle which we specified in our Creating a file tutorial, the second is the actual data we wish to write to the file.

 

Lets look at some examples

 

$file = fopen("testfile.txt","w") or die("Cannot open the file");
fwrite($file,"This is a sample string\n");
fclose($file);

 

In the example above we have 3 lines to look at.

Line 1 : We create a file handle called $file and then using the fopen function we open a file called testfile.txt for writing to, if a problem occurs an error message is displayed.
Line 2 : Using the fwrite function we use the file handle $file which specifies the file and mode of operation and we then write some data into the file.
Line 3 : We close everything by using the fclose function and passing it the $file file handle.

 

Here's another example.

 

$string1 = "This is string 1\n";
$string2 = "This is string 2\n";
$file = fopen("testfile.txt","w") or die("Cannot open the file");
fwrite($file,$string1);
fwrite($file,$string2);
fclose($file);

This would create a text file which contents would be like

This is string1
This is string2

 

Lets say we open the file again and do the following

$string3 = "This is string 3\n";
$string4 = "This is string 4\n";
$file = fopen("testfile.txt","w") or die("Cannot open the file");
fwrite($file,$string3);
fwrite($file,$string4);
fclose($file);

 

What do you think you will see , 4 lines of text. Well in fact no if you remember from previous tutorials in fact we have opened the file in "w" mode and the previous 2 lines of text will now be gone and we will now see

This is string3
This is string4

To avoid this happen you would change the code above to

$string3 = "This is string 3\n";
$string4 = "This is string 4\n";
$file = fopen("testfile.txt","a") or die("Cannot open the file");
fwrite($file,$string3);
fwrite($file,$string4);
fclose($file);