PHP fwrite()没有写任何文件,但没有给出错误

时间:2014-01-31 15:25:24

标签: php html5 fopen fwrite chmod

我正在使用php将html5文本区域的内容写入本地服务器上的文件。我已经包含了对fileExists,fileIsWritable和fileisReadble的检查,但它们都通过了,但目标文件中没有文本。

HTML

<form id = "notesForm" action = "notes.php" method = "POST">
        <textarea id = "textArea" name = "text"></textarea>
        <button type="submit" value="save"> Save</button>
</form>

PHP

$filename = 'file://localhost/Library/WebServer/Documents/Notes/test.txt';
$somecontent =  $_POST["text"];

  if (is_readable($filename)) {
                echo "<br />The file is readable...<br />";
        } else {
                echo "<br />The file is not readable...<br />";
        }

        if (is_writable($filename)) {
                echo "The file is writable...<br />";
        } else {
                echo "The file is not writable...<br />";
        }

        if (file_exists($filename)) { 
                echo "File exists...<br />";
        } else {
                echo "File cannot be found...<br />";
        }


    // make sure the file exists and is writable first.
    if (is_writable($filename)) {

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

        // Write $somecontent to our opened file.
        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";
    }

输出:
该文件是可读的...
该文件是可写的...
文件存在...
成功,写了(gfnhfghgf)到文件(文件://localhost/Library/WebServer/Documents/Notes/test.txt)


文件test.txt显示为空,任何人都可以看到问题所在吗?

由于

2 个答案:

答案 0 :(得分:1)

通过这个

fopen($filename, 'r')

您正在打开要读取的文件。如果你想写信,你应该尝试类似

的东西
fopen($filename, 'w')

或您可以在此处的手册页上找到的任何其他变体:http://php.net/fopen

答案 1 :(得分:1)

您正在以只读模式('r')打开文件。

尝试:

fopen($filename, 'w')