Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php fread() function not returning anything

I have a simple AJAX function being called when a user clicks a button that sends the text of a HTML textarea and alerts the 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);
};

as well as a PHP script on the backend which is supposed to write the received text to a file and echo the file's content:

<?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 response is empty. I tried echoing a hardcoded string instead of fread()and it worked, I also tried echoing filesize($filename)which worked perfectly fine as well.
The POST data sent by the AJAX function gets through as well, and the fwrite($fh, $text) function does exactly what it is supposed to.
What am I doing wrong?

like image 380
Parzival Avatar asked Nov 24 '25 20:11

Parzival


1 Answers

You didn't rewind your file:

  1. you open your file for writing
  2. you write out some text - file pointer is at the END of the file
  3. you try to read some text from the file, but the pointer is at the END of the file
  4. 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');

The "can't read file" is all fine and dandy, but all of the open/write/read business is redundant and can be reduced to the above two lines of code.

like image 151
Marc B Avatar answered Nov 26 '25 09:11

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!