PHP File Handling

Reading a whole file

PHP
<?php
  $text = file_get_contents(__DIR__ . '/notes.txt');
  echo $text;

  $lines = file(__DIR__ . '/notes.txt', FILE_IGNORE_NEW_LINES);
  foreach ($lines as $line) { echo $line . "<br>"; }

Writing

PHP
<?php
  file_put_contents(__DIR__ . '/log.txt', "Hello\n");            // overwrite
  file_put_contents(__DIR__ . '/log.txt', "More\n", FILE_APPEND); // append

The fopen family

For large files, read a line at a time instead of loading everything into memory:

PHP
<?php
  $fh = fopen(__DIR__ . '/big.csv', 'r');
  if ($fh) {
      while (($line = fgets($fh)) !== false) {
          echo $line;
      }
      fclose($fh);
  }

Modes: r read, w write (truncates!), a append, x create-only, and add + for read-write.

CSV

PHP
<?php
  $fh = fopen(__DIR__ . '/students.csv', 'r');
  while (($row = fgetcsv($fh)) !== false) {
      echo $row[0] . ' — ' . $row[1] . '<br>';
  }
  fclose($fh);

Checking before acting

PHP
<?php
  if (file_exists($path))  { }
  if (is_readable($path))  { }
  if (is_writable($path))  { }
  echo filesize($path);
  unlink($path);   // delete

Security: never build a path from user input

PHP
<?php
  // DANGEROUS — ?file=../../../../etc/passwd
  // echo file_get_contents($_GET['file']);

  // SAFE — whitelist
  $allowed = ['terms' => 'terms.txt', 'privacy' => 'privacy.txt'];
  $key = $_GET['doc'] ?? '';

  if (isset($allowed[$key])) {
      echo file_get_contents(__DIR__ . '/docs/' . $allowed[$key]);
  }

This class of bug — path traversal — is one of the most common ways PHP sites get compromised. A whitelist beats any amount of filtering.