Reading and Writing Files in PHP

Tutorial 1 of 5

Introduction

In this tutorial, we will learn how to read from and write to files using PHP, which is a critical part of almost any web-based application. By the end of this tutorial, you will be able to manipulate file data in your PHP applications.

Prerequisites:
- Basic knowledge of PHP syntax
- Familiarity with running PHP in a local development environment

Step-by-Step Guide

There are several ways to handle files in PHP. The most common methods are fopen(), fwrite(), and fclose().

  • fopen() function is used to open a file
  • fwrite() is used to write data to a file
  • fclose() is used to close an open file

Best practices and tips:
Always remember to close any files that you have opened. Leaving files open could lead to memory leaks or other problems.

Code Examples

Example 1: Writing to a File

<?php
$file = fopen("testfile.txt", "w");  // Open a file for writing

if( $file == false ) {
   echo ( "Error in opening new file" );
   exit();
}

fwrite( $file, "This is  a simple test\n" );  // Write data to the file
fclose( $file );  // Close the file
?>

In this example, we open a file named "testfile.txt" for writing. If the file cannot be opened, an error message is displayed and the script exits. We then write some data to the file and finally, close the file.

Example 2: Reading from a File

<?php
$file = fopen("testfile.txt", 'r'); // Open the file for reading

if( $file == false ) {
   echo ( "Error in opening file" );
   exit();
}

$filesize = filesize( "testfile.txt" );
$filetext = fread( $file, $filesize );
fclose( $file );

echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>

In this example, we open the "testfile.txt" file for reading. If the file cannot be opened, an error message is displayed and the script exits. We then read the entire file into a string using fread(). Finally, we close the file and print out the contents.

Summary

In this tutorial, we've learned how to read from and write to files in PHP. We've covered the basic functions used in file handling and shown you how to handle common errors.

Practice Exercises

  1. Exercise: Write a PHP script that opens a file, writes your name in it, then closes it.
  2. Exercise: Write a PHP script that opens the file from exercise 1 and reads the content.

Solutions:

  1. Writing to a file:
<?php
$file = fopen("myfile.txt", "w");

if( $file == false ) {
   echo ( "Error in opening new file" );
   exit();
}

fwrite( $file, "Your Name" ); 
fclose( $file );
?>
  1. Reading from a file:
<?php
$file = fopen("myfile.txt", 'r');

if( $file == false ) {
   echo ( "Error in opening file" );
   exit();
}

$filesize = filesize( "myfile.txt" );
$filetext = fread( $file, $filesize );
fclose( $file );

echo ( "<pre>$filetext</pre>" );
?>

For further practice, try writing and reading different kinds of data, like CSV or JSON data. See if you can parse this data into a useful format.