Page 1 of 1

probably easy fwrite question

Posted: Thu Jul 22, 2004 12:17 pm
by mrdk
Hello
I'm new with PHP and I was trying to append to a file. this is what I have

test.php

Code: Select all

<?php
$filename = 'test.txt';
$somecontent = "Add this to the file";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

   // In our example we're opening $filename in append mode.
   // The file pointer is at the bottom of the file hence 
   // that's where $somecontent will go when we fwrite() it.
   if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
   }

   // Write $somecontent to our opened file.
   if (fwrite($handle, $somecontent)  === FALSE) {
       echo "Cannot write to file ($filename)";
       exit;
   }

   echo "Success, wrote ($somecontent) to file ($filename)";
   
   fclose($handle);
                   
} else {
   echo "The file $filename is not writable";
}
?>
thats from the manual. I also have a file called test.txt with all access rights on. when I run this script I get "Success, wrote (Add this to the file) to file (test.txt) " but test.txt is still blank.
any ideas what I did wrong?

Posted: Thu Jul 22, 2004 12:19 pm
by feyd
try it with 'ab' instead of 'a' in the call to fopen

Posted: Thu Jul 22, 2004 3:00 pm
by mrdk
Thanks for the reply.
I tried what you said and same thing. but I think I figured out what was causing the problem. I'm not sure why this worked but the text.txt file had 0 bytes in it so I opened it and wrote one character in it then saved it again. then when I tried the php script again it worked. do you know why it would be like that?
thanks for the help

Posted: Thu Jul 22, 2004 3:40 pm
by feyd
not sure.. might have something to do with the file pointers on the OS.. :?