PHP File Handling Cheat Sheet

Accessing Directory

Read Directory Files into Array

$dir = 'example';
$files = scandir($dir, 'w') or die('Cannot read directory: '.$dir);
//implicitly creates file
foreach ($files as $file) {
//do something with $file
}


Open and Close Directory

$dir = 'example';
if ($dh = opendir($dir)) {
 while (($file = readdir($dh)) !== false) {
 if (substr($file, 0, 1) !== '.') {
 //do something with $file
 }
 }
 closedir($dh);
}

Accessing Files

Create a File

$file = 'file.txt';
$fh = fopen($file, 'w') or die('Cannot open file: '.$file);
//implicitly creates file
fclose($fh);

Open and Close a File

$file = 'file.txt';
$fh = fopen($file, 'w') or die('Cannot open file: '.$file);
//open file ('w','r','a')... see mode below
fclose($fh);

Read a File

$file = 'file.txt';
$fh = fopen($file, 'r');
$data = fread($fh,filesize($file));
fclose($fh);

Write to a File

$file = 'file.txt';
$fh = fopen($file, 'w') or die('Cannot open file: '.$file);
$data = 'This is the data';
fwrite($fh, $data);
fclose($fh);

Append to a File

$file = 'file.txt';
$fh = fopen($file, 'a') or die('Cannot open file: '.$file);
$data = 'New data line 1';
fwrite($fh, $data);
$new_data = "\n".'New data line 2';
fwrite($fh, $new_data);
fclose($fh);

Delete a File

$file = 'file.txt';
unlink($file)

File Modes

ModesDescription
r Open a file for read only. File pointer starts at the beginning of
the file
wOpen a file for write only. Erases the contents of the file or
creates a new file if it doesn’t exist. File pointer starts at the
beginning of the file
aOpen a file for write only. The existing data in file is preserved.
File pointer starts at the end of the file. Creates a new file if the file
doesn’t exist
xCreates a new file for write only. Returns FALSE and an error if
file already exists
r+Open a file for read/write. File pointer starts at the beginning of
the file
w+Open a file for read/write. Erases the contents of the file or
creates a new file if it doesn’t exist. File pointer starts at the
beginning of the file
a+Open a file for read/write. The existing data in file is preserved.
File pointer starts at the end of the file. Creates a new file if the file
doesn’t exist
x+Creates a new file for read/write. Returns FALSE and an error if
file already exists

Leave a Comment