Php fread () function returns nothing
I have a simple AJAX function called when the user clicks on a button that sends the HTML textarea text and warns of a response from the backend:
send_button.onclick = function ()
{
var ajax = new XMLHttpRequest();
var text = text_input.value;
ajax.onreadystatechange = function ()
{
if (ajax.readyState == 4 && ajax.status == 200) alert(ajax.responseText);
};
ajax.open("POST", "write.php", true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send("text=" + text);
};
and also a PHP script on the backend, which should write the resulting text to a file and repeat the contents of the file:
<?php
$filename = "preview/preview.html";
$text = (isset($_POST["text"]) ? $_POST["text"] : "");
try
{
$fh = fopen($filename, "w+");
if (!$fh) throw new Exception("File open error");
fwrite($fh, $text);
$filetext = (filesize($filename) > 0 ? fread($fh, filesize($filename)) : "");
echo $filetext;
fclose($fh);
}
catch (Exception $e)
{
header("Location: error.php");
}
?>
But every time the answer is empty. I tried repeating the hardcoded line instead fread()
and it worked, I also tried echoing filesize($filename)
which worked fine.
The POST data sent by the AJAX function also goes through, and the function fwrite($fh, $text)
does exactly what it should.
What am I doing wrong?
source to share
You haven't rewound your file:
- you open the file for writing
- you write out some kind of text file pointer to the END of the file
- you are trying to read some text from a file, but the pointer is at the end of the file
- no data is read, so you output an empty string
Why not use something more like this:
file_put_contents('preview/preview.html', $_POST['text'], FILE_APPEND);
readfile('preview/preview.html');
"Unable to read file" is fine and dandy, but all open / write / read operations are redundant and can be reduced to the above two lines of code.
source to share