0

I am very new to php just starting learning from internet. I seen some examples for file handling. But when I'm following the same procedure to file writing it's not working.

The Reading function is working file. But writing to a file isn't working. I have also tried to use file_put_content function to write. :(

<?php
    if(isset($_POST['submit1'])){
    $fileName = "Text.txt";
    $fh = fopen($fileName,"a") or die("can not open the file to write");

    //Writing to a file
    $newData = "Hello This is new Data";
    fwrite($fh,$newData);
    fclose($fh);

    //Reading a file -- Working
    $text = fopen("Text.txt","r") or die ("can not open the file to read");     
    while(!feof($text))
    {
        $myLine = fgets($text);
        print $myLine;
    }
    fclose($text);
    }

?>

Please Guide me.. Thanks

8
  • It's not working because it shows "can not open the file to write" ? Commented Aug 14, 2012 at 9:37
  • You should check your folder/file permissions - does the account have access to that file to write? Post the error message you are getting to help pin down the problem. Commented Aug 14, 2012 at 9:38
  • Yes this message is appearing in file writing section. but in file reading case it is working fine. Commented Aug 14, 2012 at 9:39
  • What is the error you are getting? It is probably a rights matter, try to give the folder you are working in extra rights (look into chmod). But be careful, don't go around and give everything all rights to everything. This will create a big security risk! Commented Aug 14, 2012 at 9:39
  • 1
    what errors are you getting, what user is running the script? Does the user have write access? BTW: it's file_put_contents, with an s at the end. Also read this since you're new, there's no point in learning bad practices Commented Aug 14, 2012 at 9:42

1 Answer 1

1

This works fine, what is the error you get ?

  <?php
    $file = 'text.txt';
    $writer = fopen($file, 'a');
    $addData = 'This is a new string to be added at the end of the file';
    fwrite($writer, $addData);
    fclose($writer);
  ?>

EDIT1: To Enter the input from POST request you can do something like this:

    <?php
      if ($_SERVER['REQUEST_METHOD'] == 'POST'){
        $addData = $_POST['input-name'];
        $file = 'text.txt';
        $writer = fopen($file, 'a');

        fwrite($writer, $addData);
        fclose($writer);
      }
    ?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.