2

I want my php file to write some text to a text file that I have created but nothing is being written to it.

Here is the code:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', '1');

    if (isset($_POST['comment']))
    {
        $comment = $_POST['comment'];

        $myFile = "testFile.txt";
        $fh = fopen($myFile, 'w') or die("can't open file");
        $stringData = $comment;
        fwrite($fh, $stringData);
        fclose($fh);
    }
    else
    {
        $comment = 'no comment';

        $myFile = "testFile.txt";
        $fh = fopen($myFile, 'w') or die("can't open file");
        $stringData = $comment;
        fwrite($fh, $stringData);
        fclose($fh);
    }
?>
5
  • What happens when you try? Is PHP even able to write to the file?
    – dpk2442
    Commented Jun 3, 2012 at 19:50
  • Well, nothing is being written to the file but it's returning no errors at all :o/
    – Satch3000
    Commented Jun 3, 2012 at 19:51
  • You should check fwrite() to see if it returns false or 0, to see if it's not writing anything or if there's an error writing.
    – Litty
    Commented Jun 3, 2012 at 19:51
  • 1
    Are you sure $_POST['comment'] is not an empty string?
    – Ruben
    Commented Jun 3, 2012 at 19:53
  • When you fopen() your file with "w" mode parameter you are telling PHP to cleanup the txt file or attempt to create it. If the data passed to the fwrite() function is empty, your output file will obviously be empty.
    – dAm2K
    Commented Jun 3, 2012 at 20:17

1 Answer 1

2

Check the file permissions.

Try changing permission if that was the issue:

chmod("testFile.txt", 0644);
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.