开发者

fwrite to txt-file

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 anyb开发者_开发技巧ody know how to troubleshoot a situation like this?


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜