Basics on how to open, read, write and close files in PHP?

Lets say we would like to open a file and print one line from it.

To do this you first have to open a file using fopen funtion. The fopen() function opens a file or URL.

<?php
$file = fopen("test.txt","r");
$file = fopen("/home/test/test.txt","r");
$file = fopen("/home/test/test.gif","w+");
$file = fopen("http://www.example.com/","r");
$file = fopen("ftp://user:password@example.com/test.txt","w");
?>

the second argument in the function above is the mode in which you want to open the file. You can open the file only for reading, only for writing, for appending, for reading and writing etc as explained below:
Possible values:

  • “r” (Read only. Starts at the beginning of the file)
  • “r+” (Read/Write. Starts at the beginning of the file)
  • “w” (Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist)
  • “w+” (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn’t exist)
  • “a” (Write only. Opens and writes to the end of the file or creates a new file if it doesn’t exist)
  • “a+” (Read/Write. Preserves file content by writing to the end of the file)
  • “x” (Write only. Creates a new file. Returns FALSE and an error if file already exists)
  • “x+” (Read/Write. Creates a new file. Returns FALSE and an error if file already exists)

Once you open the file using fopen() it will return a pointer ($file) to the right location in the file from where you can start reading and writing.

Now that the file is open you can read from it. There are many easy ways to read from a file. Normal is to read files on a line by line basis till we HIT the last character in the file which is called EOF (-1) = End Of File.

This code will print 1 line form the file and will close the file.

<?php
$file = fopen("test.txt","r");
echo fgets($file);
fclose($file); ?>

This code will print all the lines from the file and close it:

<?php $file = fopen("test.txt","r"); while(! feof($file))
{
  echo fgets($file). "<br />";
} fclose($file);
?>

What we do above is we go in a loop and read a line and print it and move ahead in the file line by line. feof() function will check if the file pointer $file points to EOF? If it does not that means we have not hit the end of the file so we can read in one more line.
More here: http://www.w3schools.com/php/func_filesystem_fgets.asp

For writing in a file there are many functions too. Here is one easy way to do it using fputs() function:

<?php
$file = fopen("test.txt","w");
echo fputs($file,"Hello World. Testing!");
fclose($file);
?>

You should always close the file once you have finished operating on it using the fclose() function.