PHP Tutorial · PHP for the Web · Lesson 23 of 38
PHP File Handling
Read, write and append files, and work with CSV.
Reading and writing whole files
file_put_contents() and file_get_contents() are the simplest tools:
<?php
$path = sys_get_temp_dir() . "/notes.txt";
file_put_contents($path, "First line\n");
file_put_contents($path, "Second line\n", FILE_APPEND);
echo file_get_contents($path);
$lines = file($path, FILE_IGNORE_NEW_LINES);
echo count($lines), " lines; last: ", end($lines), "\n";
unlink($path);
var_dump(file_exists($path));
Output
First line Second line 2 lines; last: Second line bool(false)
Line by line
file() returns an array of lines. For big files, open a handle with fopen() and read with fgets() so you don't load everything into memory.
CSV files
<?php
$path = sys_get_temp_dir() . "/orders.csv";
$fh = fopen($path, "w");
fputcsv($fh, ["id", "customer", "total"]);
fputcsv($fh, [1, "Ada", 42.5]);
fputcsv($fh, [2, "Lin, Jr.", 19.99]);
fclose($fh);
$fh = fopen($path, "r");
$header = fgetcsv($fh);
while (($row = fgetcsv($fh)) !== false) {
$order = array_combine($header, $row);
echo "#{$order['id']} {$order['customer']}: {$order['total']}\n";
}
fclose($fh);
Output
#1 Ada: 42.5 #2 Lin, Jr.: 19.99
Checking files
file_exists(), is_file(), is_dir(), filesize() and unlink() (delete). Always check whether a file exists before reading it, and never build paths from raw user input.
Test yourself
Which flag makes file_put_contents() add to the end of a file?
FILE_ADDFILE_APPENDAPPEND_MODEFILE_END
Show answer
Answer: FILE_APPEND
Practice next
- Revenue Report from CSV · coding problem