Quick read and write
$text = file_get_contents('data.txt'); // whole file as string (false on error)
file_put_contents('data.txt', $text); // overwrite (creates file)
file_put_contents('log.txt', "line\n", FILE_APPEND | LOCK_EX); // append with lock
$lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); // array of linesfile_get_contents also reads URLs (https://…) if allow_url_fopen is on.
Line by line (large files)
$fh = fopen('big.log', 'r');
if ($fh === false) { die('Cannot open'); }
while (($line = fgets($fh)) !== false) {
echo trim($line), PHP_EOL;
}
fclose($fh);| Mode | Meaning |
|---|---|
r | read |
r+ | read and write |
w | write, empties the file / creates it |
a | append / creates it |
x | create, fails if it exists |
c | write without emptying |
Other handle functions: fwrite($fh, $s), fread($fh, $bytes), feof($fh), flock($fh, LOCK_EX), rewind($fh).
CSV
// read
$fh = fopen('users.csv', 'r');
$header = fgetcsv($fh, null, ';');
while (($row = fgetcsv($fh, null, ';')) !== false) {
$user = array_combine($header, $row);
}
fclose($fh);
// write
$fh = fopen('out.csv', 'w');
fputcsv($fh, ['id', 'name'], ';');
fputcsv($fh, [1, 'Anna'], ';');
fclose($fh);Checking files
| Function | Returns |
|---|---|
file_exists($p) | file or folder exists |
is_file($p) / is_dir($p) | is a file / folder |
is_readable($p) / is_writable($p) | permissions |
filesize($p) | size in bytes |
filemtime($p) | last change (timestamp) |
mime_content_type($p) | e.g. image/png |
PHP caches these results; call clearstatcache() if a file changes during the script.
Managing files and folders
| Function | Does |
|---|---|
copy($from, $to) | copy a file |
rename($from, $to) | move or rename |
unlink($p) | delete a file |
mkdir($p, 0755, true) | create folder (true = with parents) |
rmdir($p) | delete an empty folder |
scandir($dir) | list entries (includes . and ..) |
glob('img/*.{jpg,png}', GLOB_BRACE) | list by pattern |
chmod($p, 0644) | set permissions |
tempnam(sys_get_temp_dir(), 'pre') | create a temp file |
Recursive listing:
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('src', FilesystemIterator::SKIP_DOTS));
foreach ($it as $file) {
echo $file->getPathname(), PHP_EOL;
}Paths
| Helper | Example result for /var/www/img/logo.png |
|---|---|
basename($p) | logo.png |
dirname($p) | /var/www/img |
pathinfo($p, PATHINFO_EXTENSION) | png |
pathinfo($p, PATHINFO_FILENAME) | logo |
realpath('../x') | absolute path or false |
__DIR__ / __FILE__ | folder / path of the current script |
DIRECTORY_SEPARATOR | / or \ |
File uploads
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
$mime = mime_content_type($_FILES['file']['tmp_name']);
if (in_array($mime, ['image/png', 'image/jpeg'], true)) {
$target = __DIR__ . '/uploads/' . bin2hex(random_bytes(8)) . '.' . $ext;
move_uploaded_file($_FILES['file']['tmp_name'], $target);
}
}Never trust the original file name or the browser's type; generate your own name and check the real MIME type. Form needs enctype="multipart/form-data". Limits: upload_max_filesize and post_max_size in php.ini.
Previous: PHP Date and Time · Next: PHP Forms, Sessions, Cookies and Security
Put together with AI as a quick reference I keep for my own work. Entries like this are usually not reviewed in detail by a person.