I'm running php 5.0.1 on the default install of Apache on Mac OS X Panther.

I'm trying to write to a file with fwrite() but nothing I do works. However, I can write to a file with file_put_contents, so I'm pretty sure it's not permissions.

Here's what I think should work...

<?php
$junk = 'I am going to try to write this string to the file';
$filename = 'junk.txt';
fopen($filename, 'ab');
fwrite($filename, $junk);
fclose($filename);
?>

...but it doesn't. It creates the file but the file remains empty.

This does work however...

<?php
$junk2 = 'I am going to try to write this string to the file';
$filename2 = 'junk2.txt';
file_put_contents($filename2, $junk2);
?>

...but it overwrites anything that was there before it.

I just don't know what is going on. I've tried a, a+, w, w+, r+, and all of those with b on the end as well.

If you don't know why fwrite isn't working, perhaps you could tell me how to make file_put_contents append. The php manual isn't very clear on how to make it append.

Help me unleash the power of php, help me fwrite! 😃

    You need to use a resource handle with "fopen()":

    $junk = 'I am going to try to write this string to the file'; 
    $filename = 'junk.txt'; 
    $resource_handle = fopen($filename, 'ab'); 
    fwrite($resource_handle, $junk); 
    fclose($resource_handle);

    Or:

    $junk2 = 'I am going to try to write this string to the file'; 
    $filename2 = 'junk2.txt';
    file_put_contents($filename2, $junk2, FILE_APPEND);

      Installer...

      THANK YOU so very very much. I've been working on this since last night to no avail, what a life saver you are!

      I knew it had to be something I wasn't opening right since file put worked. Really though man, I just can't thank you enough.

      ...Flynn

        Write a Reply...