PHP ยท Chapter 29 of 44

PHP File Handling

PHP can read from and write to files on the server using functions like fopen(), fread(), fwrite(), and fclose(). This is useful for logging, storing simple data, or generating reports without a database.

Always open files with the correct mode (like "r" for read, "w" for write, or "a" for append) and close them with fclose() when finished to free system resources.

Syntax
$fh = fopen("file.txt", "r");
fwrite($fh, "text");
fclose($fh);

Reading files

fopen($file, "r") opens a file for reading, fread() reads its content, and file_get_contents() offers a simpler one-line way to read an entire file into a string.

Writing files

fopen($file, "w") opens (and creates if needed) a file for writing, overwriting existing content, while "a" mode appends to the end instead.

Example 1 (php)
<?php
  file_put_contents("notes.txt", "Hello File!");
  echo file_get_contents("notes.txt");
?>
Output
Hello File!

file_put_contents() writes text to a file, and file_get_contents() reads it back.

Example 2 (php)
<?php
  $fh = fopen("log.txt", "a");
  fwrite($fh, "New entry\n");
  fclose($fh);
  echo "Logged!";
?>
Output
Logged!

Opening in append ("a") mode adds new content to the end of the file without erasing it.

Key points

  • fopen() opens a file, and fclose() closes it when done.
  • file_get_contents() and file_put_contents() offer simple one-line read/write operations.
  • Mode "r" reads, "w" overwrites, and "a" appends to a file.
  • Always close files to release system resources.
๐Ÿ’ก Note: Check that your script has proper file system permissions, or file operations will silently fail or throw warnings.

๐Ÿ“ Quick Quiz

1. Which function opens a file for reading or writing?

2. Which mode appends to the end of a file instead of overwriting it?

3. Which function reads an entire file into a string in one call?