PHP : File Open/Read/Close

Working with files in PHP involves opening, reading, and closing files. Here's a simple example of how to do this:

1. Opening a File:

You can open a file using fopen(). This function takes two parameters: the filename and the mode (how you want to open the file).


$filename = "example.txt";
$file = fopen($filename, "r") or die("Unable to open file!");

 

  • r: Opens the file for reading.
  • w: Opens the file for writing. Creates a new file or truncates an existing file to zero length.
  • a: Opens the file for writing. Creates a new file or appends to an existing file.
  • x: Creates a new file for writing. Returns FALSE and an error if the file already exists.

2. Reading from a File:

Reading Entire File:


You can use file_get_contents() to read the entire contents of a file into a string.


$content = file_get_contents($filename);
echo $content;

 

Reading Line by Line:


If you want to read the file line by line, use fgets() inside a loop until the end of the file.


$file = fopen($filename, "r") or die("Unable to open file!");
while(!feof($file)) {
    echo fgets($file) . "<br>";
}
fclose($file);

 

3. Closing a File:

Always remember to close the file when you are done with it, using fclose().


fclose($file);
 

Complete Example:

Here's a complete example that reads the contents of a file line by line and then closes the file:


<?php
$filename = "example.txt";
$file = fopen($filename, "r") or die("Unable to open file!");
while(!feof($file)) {
    echo fgets($file) . "<br>";
}
fclose($file);
?>

 

In this example:

  • The script opens the file example.txt in read mode.
  • It reads each line of the file using fgets() inside a while loop.
  • When it reaches the end of the file ( feof() ), the loop ends.
  • Finally, the file is closed with fclose().

Remember to handle errors gracefully when working with files, especially when opening and reading them, as failure to open a file could cause your script to terminate unexpectedly.