Reputation: 819
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
Upvotes: 1
Views: 1660
Reputation: 19103
You are opening the file in readonly mode ('r').
Try:
fopen($filename, 'w')
Upvotes: 0
Reputation: 5397
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
Upvotes: 1