Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Writing to Files With fwrite()

So we now know how to read file contents - and close files. Now let's see about writing to files.

To write to a file we use the fwrite() function whose syntax is:

$successOrFail = fwrite($file_handle, "what_to_write");

Of course you will only be able to write to a file if you opened it in 'write' or 'read/write' mode. You will therefore need to open it with the mode set to either:

'r+'  - read/write - no truncate, pointer at beginning
'w'   - write only - truncates file, pointer at beginning, attempts creation
'w+'  - read/write - truncates file, pointer at beginning, attempts creation
'a'   - write only - no truncate, pointer at end of file, attempts creation
'a+'  - read/write - no truncate, pointer at end of file, attempts creation

What does this mean?

truncates file means that ALL the existing file contents in the specified file will be erased
pointer beginning/end means the pointer (cursor?) inside the file will be at the beginning or at the end. If the cursor is at the beginning then new additions are added at the top of the file, and when the pointer is at the end the new additions will be placed at the bottom of the file.
attempts creation means that if the file does not exist, then PHP will attempt to create it.

The following code snippet opens a file for writing only, positioning the cursor at the end of the file. It then adds a new line of text (timestamp) into the file, before closing it:

...
$now = getdate();
$file2open = "/www/home/list.txt";
if(!$listfile = fopen($file2open, 'a') ){
	print ("cannot open $file2open for writing";
 } else {
	fwrite($listfile,"\nThis line added at $now");
  	if(!fclose($listfile)){
	  print "cannot close $file2open";
	}
 }
...

If you remember, the getdate() function was covered earlier in which case we said that it returns (gives back) the system date. The only line of code that is new here is the one that reads:

fwrite($listfile, "\nThis line added at $now");

On this line we first write a new line character(\n) and then the words "This line added at $now" where $now is the current system date gotten using getdate().

Let's take a peek at some more file management functions.

<< Reading From Files | More Functions >>

JamHitz Productions