tags:

views:

103

answers:

2

I'm currently trying to write to a txt-file with PHP, I've found this small script:

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

if (is_writable($filename)) {

    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    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";
}
?>

I get a success-message, but nothing is written to the file. Even if I delete the txt-file I still get the success-message

Does anybody know how to troubleshoot a situation like this?

+2  A: 

Your code works perfectly fine. However, note that the is_writable check will fail if the file does not exist yet.

If you execute it through a webserver, make sure you are not viewing a cached response.

ThiefMaster
(just thought of the response being cached myself)
Joel L
I'm executing the script through a webserver - sorry for being a n00b but how do avoid viewing a cached response?
timkl
Send headers which prevent caching or, if it's just for you, you can just reload it with CTRL+F5
ThiefMaster
+2  A: 

Your first check with is_writable is not useful, as it fails if the file does not exist. When you use fopen with the "a" parameter you appent to the file if it exists otherwise it will create a new one.

If you want to check if the file exists you can with file_exists ( http://php.net/manual/en/function.file-exists.php ), but it is not really necessary.

With your code, if you delete the file you should actually get a "the file is not writable" error... are you sure you have exactly that code?

Otherwise, I tried the code and it works fine (without the first if).

nico