File Handling with PHP

A file is created or opened for reading or writing in PHP using the fopen() function. The fopen() function accepts two parameters. The first is the name of the file to be opened, and the second specifies the mode in which the file should be opened. The fopen() function also returns a pointer (or file handle) that is used to access the file in subsequent file operations. If the file cannot be opened for any reason, it returns 0 (FALSE). The following PHP script can be used to open the file:


<html>
  <body>

<?php
  $myFile=fopen("mydata.txt","r") or exit("Can’t open file!");
  fclose($myFile);
?>

  </body>
</html>


Note that the fclose() function (which as the name suggests, closes a file) accepts a single argument consisting of a file handle (in this case $myFile). It is important to close a file once you have completed any necessary file operations. Enter the code above into a text editor and save it with the filename "files_01.php" in the "htdocs" directory of your "xampp" directory. Run the XAMPP server, then type the following URL into the browser’s address bar:


http://localhost/files_01.php


You should see a web page that looks something like the screenshot below.


The initial output from files_01.php

The initial output from files_01.php


Now create a text file that contains some text information (for example, your name, address, telephone number and email address). Save the file to the "htdocs" directory in your "xampp" directory with the filename "mydata.txt", and reload the script (files_01.php) in the browser. You will see a web page with no errors, but you will probably be somewhat disappointed by the result since there will be nothing to see. The script has (hopefully) succeeded in opening the file for reading, but has not done anything with it. If we want the script to do something other than simply open a file, we need to add some more code. Note from the above script that the second parameter we passed to fopen() was "r", which tells the function to open the file for reading. The table below lists the different file modes available, and gives a brief description of what each mode means.



File modes used by fopen()
ModeDescription
"r"Opens the file for reading only, and positions the
file pointer at the beginning of the file.
"r+"Opens the file for reading or writing, and positions
the file pointer at the beginning of the file.
"w"Opens the file for writing and clears the file’s
contents (or creates a new file if one does not
already exist).
"w+"Opens the file for reading or writing and clears the
file’s contents (or creates a new file if one does not
already exist).
"a"Opens the file for writing, but preserves any existing
file content and positions the file pointer at the end
of the file (creates a new file if one does not already
exist).
"a+"Opens the file for reading or writing, but preserves
any existing file content and positions the file
pointer at the end of the file (creates a new file if one
does not already exist).
"x"Creates a new file and opens it for writing. If the
file already exists, the file is not created and fopen()
returns 0 (FALSE) and generates an error message.
"x+"Creates a new file and opens it for reading or
writing. If the file already exists, the file is not
created and fopen() returns 0 (FALSE) and
generates an error message.

In order to read a file, you must have opened the file in the appropriate mode ("r", "r+", "w+", "a+" or "x+"). Once the file is open there are alternative ways to read the data. If the file is a text file, for example, you can read the file one line at a time (using the fgets() function) or one character at a time (using the fgetc() function). In both cases, it is often the case that the exact number of lines or characters in the file is not known in advance. To read all the data in the file, therefore, we can use a loop construct to read each item in turn, until there are no more items to read. It is important to be able to check whether we have reached the end of the file, however, to avoid trying to read file data beyond this point. The feof() function can be used in loop constructs to check whether the end-of-file indicator (EOF) has been reached.

The example script below will read the contents of the mydata.txt file line-by-line, and echo each line of text to the screen on a new line. Note that when the file is first opened, the file pointer is positioned at the start of the file. Each time fgets() is called, the current position of the file pointer determines which line of text will be read. Once the line has been read, the file pointer will be positioned at the start of the next line of text within the file (or at the end of the file, if the last line of text has been read).


<html>
  <body>

<?php

  $myFile=fopen("mydata.txt","r") or exit("Can’t open file!");

  // Read and display each line of text until the end of the file
  // is reached.

  while(!feof($myFile))
  {
    echo fgets($myFile) . "<br>";
  }

  fclose($myFile);

?>

  </body>
</html>


Enter the code above into a text editor and save it with the filename "files_02.php" in the "htdocs" directory of your "xampp" directory. Run the XAMPP server, then type the following URL into the browser’s address bar:


http://localhost/files_02.php


You should see a web page that looks something like the screenshot below.


The output from files_02.php

The output from files_02.php


The next example script (below) is a slightly modified version of the previous script that uses the fgetc() function in place of fgets(). It will read the contents of the mydata.txt file character-by-character, and echo each character to the screen one after the other. As before, when the file is first opened, the file pointer is positioned at the start of the file. Each time fgetc() is called, the current position of the file pointer determines which character will be read. Once the character has been read, the file pointer will be advanced so that it points to the next character in the file (or at the end of the file, if the last character has been read).


<html>
  <body>

<?php

  $myFile=fopen("mydata.txt","r") or exit("Can’t open file!");

  // Read and display each line of text until the end of the file
  // is reached.

  while(!feof($myFile))
  {
    echo fgetc($myFile);
  }

  fclose($myFile);

?>

  </body>
</html>


Enter the code above into a text editor and save it with the filename "files_03.php" in the "htdocs" directory of your "xampp" directory. Run the XAMPP server, then type the following URL into the browser’s address bar:


http://localhost/files_03.php


You should see a web page that looks something like the screenshot below.


The output from files_03.php

The output from files_03.php