Question

I am writing the contents of a html5 text area to a file on a local server using php. I have included checks for fileExists, fileIsWritable and fileisReadble and they all pass, however no text appears in the target file.

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

output:
The file is readable...
The file is writable...
File exists...
Success, wrote ( gfnhfghgf) to file (file://localhost/Library/WebServer/Documents/Notes/test.txt)


The file test.txt appears empty, can anyone see what the problem is?

Thanks

Was it helpful?

Solution 2

You are opening the file in readonly mode ('r').

Try:

fopen($filename, 'w')

OTHER TIPS

By this

fopen($filename, 'r')

You are opening the file to read from. If you want to write to it you should try something like

fopen($filename, 'w')

or any other variation you can find on the man page here: http://php.net/fopen

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top