This chapter will explain the following file-related functions -

  • Opens the file
  • Reading file
  • Writing a file
  • Closing file

Opening and Closing Files

The PHP function fopen() is used to open a file. It requires two arguments that specify the file name and the mode in which it should work.

File paths can be specified as one of the six options in this table.

ModeĀ Purpose
rOpens the file for reading only. Places the file pointer at the beginning of the file.
r++Opens the file for reading and writing. Places the file pointer at the beginning of the file.
wOpens the file for writing only. Places the file pointer at the beginning of the file. and truncates the file to zero length. If files does not exist then it attempts to create a file.
w++Opens the file for reading and writing only. Places the file pointer at the beginning of the file. and truncates the file to zero length. If files does not exist then it attempts to create a file.
aOpens the file for writing only. Places the file pointer at the end of the file. If files does not exist then it attempts to create a file.
a++Opens the file for reading and writing only. Places the file pointer at the end of the file. If files does not exist then it attempts to create a file.

Reading a file

Once the file is opened using the fopen () function it can be read with a function called fread (). This task requires two arguments. This should be a file identifier and file lengths expressed in bytes.

File lengths can be obtained using the filesize () function which takes the file name as its argument and returns the file size expressed by bytes.

So here are the steps needed to read a file with PHP.

  • Open the file using the fopen() function.
  • Find the file length using the filesize() function.
  • Read the contents of the file using the fread function().
  • Close the file with fclose() function.

The following example provides the text file content of a variable and displays that content on a web page.

<?php

$filename = "tmp.txt";
$file = fopen($filename, "r");

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

$filesize = filesize($filename);
$filetext = fread($file, $filesize);
fclose($file);

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

Output:

File size : 120 bytes
PHP is a general-purpose scripting language especially suited to web development.

Writing a file

A new file can be written or text can be added to an existing file using the PHP fwrite() function.

The following example creates a new text file and writes a short text that goes inside it. After closing this file its existence is confirmed using the file_exist() function which takes the file name as an argument

<?php

$filename = "newfile.txt";
$file = fopen($filename, "w");

if ($file == false) {
    echo ( "Error in opening new file" );
    exit();
}
fwrite($file, "This is  a simple test\n");
fclose($file);
?>