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.
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.
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;
}
readfile(): Always normalize with basename() and check realpath() inside a dedicated directory.file_get_contents(): Reading huge CSV or log files into one string exhausts PHP's memory_limit. Stream large files line by line with fgets() instead.0777: Overly permissive 0777 lets any user on the server overwrite executable scripts. Use 0755 for directories and 0644 for files.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.
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.
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.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.