PHP File Handling
PHP File Handling: Inspecting and Accessing Server Files Safely
PHP file handling functions allow backend scripts to check whether files exist, inspect permissions, read configuration assets, and write application logs. Because direct disk access touches the host filesystem, every file operation should verify existence and guard against unsafe paths.
Checking Files Before Reading or Writing
Never assume a file exists or is writable before opening it. Check is_file(), is_readable(), and is_writable() first so your script handles missing assets gracefully instead of emitting raw warnings.
<?php
declare(strict_types=1);
$logFile = __DIR__ . '/storage/app.log';
if (is_file($logFile) && is_readable($logFile)) {
$bytes = filesize($logFile);
$contents = file_get_contents($logFile);
echo "Read {$bytes} bytes from log." . PHP_EOL;
} else {
echo "Log file not initialized yet." . PHP_EOL;
}
For small and medium files (configs, JSON manifests, templates), file_get_contents() and file_put_contents() handle opening, reading/writing, and closing in one atomic call.
Preventing Path Traversal Attacks
If a download endpoint accepts a filename from $_GET['file'], an attacker might pass ../../.env to read secrets. Strip directory segments with basename() and verify realpath() stays inside your allowed storage folder.
<?php
declare(strict_types=1);
function resolveSafeDownloadPath(string $baseDir, string $requestedName): ?string
{
$safeName = basename($requestedName);
$realBase = realpath($baseDir);
$realTarget = $realBase !== false ? realpath($realBase . DIRECTORY_SEPARATOR . $safeName) : false;
if ($realBase === false || $realTarget === false) {
return null;
}
return str_starts_with($realTarget, $realBase . DIRECTORY_SEPARATOR) && is_file($realTarget)
? $realTarget
: null;
}
Common Mistakes to Avoid
- Passing raw user filenames to
readfile(): Always normalize withbasename()and checkrealpath()inside a dedicated directory. - Loading multi-gigabyte files with
file_get_contents(): Reading huge CSV or log files into one string exhausts PHP'smemory_limit. Stream large files line by line withfgets()instead. - Setting folder permissions to
0777: Overly permissive0777lets any user on the server overwrite executable scripts. Use0755for directories and0644for files.
Frequently Asked Questions
What is the difference between file_exists() and is_file()?
file_exists() returns true for both files and directories, whereas is_file() returns true only when the path points to a regular file.
Why does filesize() sometimes return stale numbers after editing a file?
PHP caches file metadata per request for speed. Call clearstatcache(true, $path) after modifying a file if you need updated size or modification times immediately.
Can file_get_contents() fetch remote URLs?
Only if allow_url_fopen is enabled in php.ini. For HTTP APIs, prefer cURL or Guzzle so you get timeouts, status codes, and retry control.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.