Working with files is an essential part of web development, as you often need to read and write data to and from files on the server. In this lesson, we'll cover the basics of file input and output in PHP, including reading, writing, and modifying files.

Opening and Closing Files

PHP provides the fopen() function to open a file and return a file handle resource. You must specify the file mode, which indicates how you intend to use the file (e.g., read, write, or append).

$file = fopen("example.txt", "r"); // Open the file for reading
fclose($file); // Close the file when done

File Modes:

Reading Files

  1. fgets(): Reads a line from the file.
$file = fopen("example.txt", "r");

while (($line = fgets($file)) !== false) {
  echo $line . "<br>";
}

fclose($file);
  1. fread(): Reads a specified number of bytes from the file.
$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt")); // Read the entire file
echo $content;
fclose($file);
  1. file_get_contents(): Reads the entire contents of a file into a string.
$content = file_get_contents("example.txt");
echo $content;

Writing Files

  1. fwrite(): Writes a string to the file.
$file = fopen("example.txt", "w");
fwrite($file, "This is a test."); // Write a string to the file
fclose($file);
  1. file_put_contents(): Writes a string to the file, creating the file if it does not exist.
file_put_contents("example.txt", "This is a test.");