·  PHP – Terms – Files – Text – Write

 

- Info:

  - This tutorial shows how to use PHP to create and write to text file.

  - If file exists data is deleted.

  - If file doesn't exists new one is created.

  - File pointer is at the begining of the file.

  - Function file_put_contents() is identical to calling fopen(), fwrite() and fclose() to write data to a file.

  - This tutorial is based on http://php.net/manual/en/function.file-put-contents.php.

 

- Simple:

  - Create PHP Console Application Test.php

 

    Test.php

    <?php

      file_put_contents('people.txt', "First line\n", LOCK_EX); //Prevent others writing simultaniously.

    ?>

 

- Complex:

  - Create PHP Console Application Test.php.

 

    Test.php

    <?php

      

      $fp = fopen("test.txt", 'w');  //Create FilePointer for writing to file.

      if($fp==false) {

        print("Unable to open or create file.");

        exit(1);

      }

   

      flock ($fp, LOCK_EX);

      fwrite($fp, "First line.\n");

      fwrite($fp, "Second line.\n");

      flock ($fp, LOCK_UN);

      fclose($fp);

      

    ?>

 

    test.txt

    First line.

    Second line.

 

    test.txt    (ASCII View)

    46 69 72 73 74 20 6C 69 6E 65 2E 0A

    53 65 63 6F 6E 64 20 6C 69 6E 65 2E 0A