PHP File Handling

PHP can create, read, write, update, and delete files on the server. This capability is used for logging events, storing configuration, writing CSV exports, and handling user uploads. PHP's file functions are straightforward, but they require proper error handling and permission awareness to work reliably.

Checking if a File Exists

Before reading or writing a file, checking that it exists prevents errors.

<?php
  $filename = "data.txt";

  if (file_exists($filename)) {
    echo "File found.";
  } else {
    echo "File does not exist.";
  }
?>

Reading Files

file_get_contents() — Read Entire File as String

This is the simplest way to read a file. It returns the entire file content as a string.

<?php
  $content = file_get_contents("notes.txt");

  if ($content !== false) {
    echo $content;
  } else {
    echo "Could not read the file.";
  }
?>

file() — Read File into Array

The file() function reads a file and returns each line as an array element.

<?php
  $lines = file("names.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

  foreach ($lines as $line) {
    echo $line . "<br>";
  }
?>

fopen(), fread(), fclose() — Manual File Reading

Opening a file manually gives more control, especially for large files that should not be loaded entirely into memory.

<?php
  $handle = fopen("report.txt", "r");   // "r" = read mode

  if ($handle) {
    while (!feof($handle)) {            // feof() checks for end of file
      $line = fgets($handle);           // Reads one line at a time
      echo $line . "<br>";
    }
    fclose($handle);                    // Always close the file
  } else {
    echo "Could not open file.";
  }
?>

Writing Files

file_put_contents() — Write String to File

This is the simplest way to write content to a file. If the file does not exist, it is created. If it does exist, it is overwritten by default.

<?php
  $data = "Hello, this is some text.";
  $bytesWritten = file_put_contents("output.txt", $data);

  if ($bytesWritten !== false) {
    echo "Wrote " . $bytesWritten . " bytes.";
  }
?>

Appending to a File

Pass the FILE_APPEND flag to add content to the end of an existing file without overwriting it.

<?php
  $logEntry = date("Y-m-d H:i:s") . " - User logged in.\n";
  file_put_contents("app.log", $logEntry, FILE_APPEND);
?>

fopen(), fwrite(), fclose() — Manual File Writing

<?php
  $handle = fopen("output.txt", "w");   // "w" = write mode (overwrites existing content)

  if ($handle) {
    fwrite($handle, "Line 1\n");
    fwrite($handle, "Line 2\n");
    fwrite($handle, "Line 3\n");
    fclose($handle);
    echo "File written successfully.";
  }
?>

File Open Modes

ModeDescription
rRead only. File must exist.
r+Read and write. File must exist.
wWrite only. Truncates file or creates new.
w+Read and write. Truncates file or creates new.
aAppend only. Creates file if not exists.
a+Read and append. Creates file if not exists.
xWrite only. Creates file. Fails if file already exists.

Working with File Metadata

<?php
  $file = "document.pdf";

  echo filesize($file);          // File size in bytes
  echo filemtime($file);         // Last modified time (Unix timestamp)
  echo date("Y-m-d", filemtime($file));   // Human-readable date
  echo pathinfo($file, PATHINFO_EXTENSION);   // "pdf"
  echo pathinfo($file, PATHINFO_FILENAME);    // "document"
  echo pathinfo($file, PATHINFO_DIRNAME);     // "." (current directory)
?>

Copying, Renaming, and Deleting Files

<?php
  // Copy a file
  if (copy("original.txt", "backup.txt")) {
    echo "File copied.";
  }

  // Rename (or move) a file
  if (rename("backup.txt", "archive/backup.txt")) {
    echo "File moved.";
  }

  // Delete a file
  if (file_exists("old_data.txt")) {
    unlink("old_data.txt");
    echo "File deleted.";
  }
?>

Practical Example — Writing a Log File

<?php
  function writeLog($message) {
    $timestamp = date("Y-m-d H:i:s");
    $logLine = "[$timestamp] $message\n";
    file_put_contents(__DIR__ . "/logs/app.log", $logLine, FILE_APPEND | LOCK_EX);
  }

  writeLog("Application started.");
  writeLog("User ID 42 logged in.");
  writeLog("Payment of $49.99 processed.");

  // Reads the log and displays all entries
  $logContent = file_get_contents(__DIR__ . "/logs/app.log");
  echo nl2br($logContent);
?>

The LOCK_EX flag acquires an exclusive lock on the file during writing, preventing corruption when multiple requests write to the same log simultaneously.

Key Points

  • Use file_exists() before reading or deleting a file to avoid errors.
  • file_get_contents() reads an entire file into a string — simple and efficient for small files.
  • file_put_contents() writes a string to a file; use FILE_APPEND to add content instead of overwriting.
  • Manual file handling with fopen(), fread()/fwrite(), and fclose() gives more control for large files.
  • Always close files opened with fopen() using fclose().
  • Use LOCK_EX when writing to shared log files to prevent data corruption.
  • copy(), rename(), and unlink() handle file copy, move, and deletion respectively.

Leave a Comment

Your email address will not be published. Required fields are marked *