Visit the Official PHP Website |
PHP ProgrammingBy James N HitzWriting 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
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. |
JamHitz Productions