Reading and Writing Files

4.63 (76)

Writing to Files

It is natural in ones life to wonder, 'how do I write to a file using PHP?' Well, here's how! In fact we are actually going to append to the file. This means that we are going to write to the end of the file, to add more content. If we were to just plain write to the file, everything would first be automatically erased and this is not so useful to us.

We need to create a form to allow new sayings to be added, and combine this with the required PHP code:

Appending File
<html>
<body>

<?php
if (isset($_POST['saying'])) {
    if (!
$file fopen('randomsayings.txt''ab')) {
        echo 
'Error whilst opening the file.';
    } else {
        if (
fwrite($file$_POST['saying'])) {
            echo 
'Saying added to file!';
        } else {
            echo 
'An error occurred whilst adding the saying.';
        }
        
fclose($file);
    }
}
?>

<br>
<br>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Saying:<br>
<textarea name="saying"></textarea><br>
<input type="submit" name="submit" value="Insert">
</form>
</body>
</html>


This example code is a full script for adding sayings to the randomsayings.txt text file. It incorporates a form, error checking and the appropriate code to add the sayings. In order to append the file (write at the end of the file), we first have to open the file using append mode or the a character. Like usual, we use the binary modifier to avoid incompatibilities. To write, we use fwrite() which takes two parameters; the file resource, and the data to be written to the file.

The above code produces something along the lines of this:



As you can see, it is not too difficult to write to the end of a file. It is though much more difficult to write to the middle of a file or to edit lines that already exists in a file – this is out of the scope of this article. If you wanted to clear a file and write to the beginning, all you have to do is use the write mode wb. Hopefully, this short introduction helps you understand the basics of reading and writing to files in PHP.
Rate this article: BAD 1 2 3 4 5   GOOD
<<     Page 3 of 3

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter