fwrite到txt文件

时间:2010-05-14 09:47:02

标签: php fwrite

我目前正在尝试使用PHP写入txt文件,我发现这个小脚本:

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

我收到了一条成功消息,但没有写入该文件。即使我删除了txt文件,我仍然会收到成功消息

有人知道如何排除这种情况吗?

2 个答案:

答案 0 :(得分:2)

您的代码完美无缺。但请注意,如果文件尚不存在,is_writable检查将失败。

如果您通过网络服务器执行,请确保您没有查看缓存的响应。

答案 1 :(得分:2)

使用is_writable进行的第一次检查无效,因为如果文件不存在则失败。 当您使用带有“a”参数的fopen时,您会将文件附加到文件,否则会创建一个新文件。

如果您想检查文件是否存在,可以使用file_existshttp://php.net/manual/en/function.file-exists.php),但这不是必需的。

使用您的代码,如果删除文件,您实际上应该得到“文件不可写”错误...您确定完全该代码吗?

否则,我尝试了代码并且工作正常(没有第一个if)。