0

我目前正在尝试使用 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 文件,我仍然会收到成功消息

有谁知道如何解决这种情况?

4

2 回答 2

2

您的代码运行良好。但是,请注意,is_writable如果文件尚不存在,则检查将失败。

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

于 2010-05-14T09:49:13.583 回答
2

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

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

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

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

于 2010-05-14T10:03:15.720 回答