File Handling & File System Functions
7 questions found
How do you read the contents of a file in PHP using functions like file_get_contents and fopen?
Beginner
file_get_contents provides a simple, convenient way to read an entire file's contents into a single string in one function call, which is perfect for smaller files, while fopen opens a file and returns a file handle that you can then read from incrementally using functions like fgets or fread, which is more appropriate for very large files where loading the entire content into memory at once would be impractical.
$content = file_get_contents('data.txt');
$handle = fopen('largefile.txt', 'r');
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
Real-world example
A configuration loader uses file_get_contents to quickly read a small settings file into memory, while a log analysis tool uses fopen and fgets to process a massive multi gigabyte log file line by line without exhausting available memory.
Common follow-ups: What is the memory difference between file_get_contents and reading a file line by line?;What happens if you forget to close a file handle after opening it?
JSON Handling in PHP;Performance Optimization & OPcache
How do you write data to a file in PHP, and what is the difference between overwriting a file and appending to it?
Beginner
file_put_contents writes data to a file, completely overwriting any existing content by default, while passing the FILE_APPEND flag instead adds the new content to the end of the existing file without removing what was already there, and the fopen function similarly supports different modes, such as w for overwriting and a for appending, giving you explicit control over exactly how your write operation should behave.
file_put_contents('log.txt', 'New entry' . PHP_EOL, FILE_APPEND);
Real-world example
A logging system appends each new log entry to the end of an existing log file using the FILE_APPEND flag, ensuring previous log history is always preserved rather than being overwritten every time a new entry is recorded.
Common follow-ups: What happens if you try to write to a file that does not yet exist?;How do file permissions affect whether PHP can successfully write to a specific file?
PHP CLI Scripting;Deployment & Hosting for PHP Applications
How do you check whether a file or directory exists, and how do you retrieve useful metadata like a file's size or last modified time?
Intermediate
The file_exists function checks whether a given path exists as either a file or a directory, while functions like filesize and filemtime retrieve specific metadata about a file, such as its size in bytes and the timestamp it was last modified, all of which are commonly used to validate assumptions before performing an operation, such as confirming a required configuration file actually exists before attempting to read it.
if (file_exists('config.php')) {
echo 'Last modified: ' . date('Y-m-d', filemtime('config.php'));
}
Real-world example
An application checks whether a specific uploaded file already exists before allowing a user to upload another file with the same name, preventing an accidental overwrite of previously uploaded content.
Common follow-ups: What is the difference between file_exists and is_file for checking specifically for a file rather than a directory?;How do you retrieve a file's permissions using PHP?
File Upload Handling;Security
How do you work with directories in PHP, including listing their contents, creating new directories, and recursively deleting them?
Intermediate
The scandir function returns an array of all files and subdirectories within a given directory, mkdir creates a new directory including the option to create nested parent directories at once, and safely deleting a directory recursively typically requires writing a custom function that first deletes all of its contents before finally removing the now empty directory itself, since PHP's built in rmdir function only works on already empty directories.
mkdir('uploads/2026', recursive: true);
$files = scandir('uploads/2026');
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') {
echo $file . PHP_EOL;
}
}
Real-world example
A file upload system organizes uploaded files into dated subdirectories, using mkdir with the recursive option to automatically create the full nested directory structure for the current year and month if it does not already exist.
Common follow-ups: Why does scandir always include the current directory and parent directory entries?;What library functions simplify recursive directory operations compared to writing your own custom recursive function?
File Upload Handling;PHP CLI Scripting
How do file locking mechanisms in PHP, using the flock function, help prevent data corruption when multiple processes might write to the same file concurrently?
Intermediate
The flock function lets you acquire an exclusive or shared lock on a file before reading from or writing to it, preventing race conditions where multiple processes or requests attempting to write to the same file simultaneously could corrupt its contents or produce inconsistent results, which is especially important for applications that use file based storage for things like counters or logs that might be accessed concurrently by multiple simultaneous requests.
$handle = fopen('counter.txt', 'c+');
if (flock($handle, LOCK_EX)) {
$count = (int) fread($handle, 1024);
ftruncate($handle, 0);
rewind($handle);
fwrite($handle, $count + 1);
flock($handle, LOCK_UN);
}
fclose($handle);
Real-world example
A simple visit counter stored as a text file uses flock to acquire an exclusive lock before reading and updating the count, preventing two simultaneous visitors from causing the counter to lose an increment due to a race condition.
Common follow-ups: What is the difference between an exclusive lock and a shared lock?;Why might a database or dedicated cache be a better solution than file based locking for high traffic scenarios?
PDO & Databases;Caching Strategies in PHP
How do stream wrappers and stream contexts in PHP allow file functions to work seamlessly with non local resources like remote URLs or cloud storage?
Advanced
PHP's stream wrapper system lets functions like file_get_contents and fopen work transparently with resources beyond the local file system, such as fetching content from a remote HTTP URL using the same familiar file functions, and stream contexts let you customize the behavior of these operations, such as setting custom HTTP headers or a timeout when reading from a remote URL, extending PHP's simple file handling functions to work with a much broader range of data sources.
$context = stream_context_create(['http' => ['timeout' => 5, 'header' => 'Authorization: Bearer token123']]);
$data = file_get_contents('https://api.example.com/data', context: $context);
Real-world example
An integration script uses file_get_contents with a custom stream context specifying an authorization header and a short timeout, retrieving data from an external API using the exact same simple function normally used for reading local files.
Common follow-ups: What other protocols besides HTTP do PHP's built in stream wrappers support?;Why might a dedicated HTTP client library be preferred over file_get_contents for more complex API interactions?
RESTful API Development with PHP;Security
What security risks are associated with file handling operations that involve user supplied file paths, and how does path traversal attack prevention work?
Advanced
A path traversal attack occurs when an attacker manipulates a file path input, often by including sequences like a double dot to navigate up directory levels, attempting to access files outside of the intended directory, such as sensitive configuration files, and preventing this requires carefully validating and sanitizing any user supplied path components, ideally by using a whitelist of allowed characters or file names rather than trying to blacklist dangerous patterns, and by resolving the final path and verifying it still falls within the intended base directory before performing any file operation.
$baseDir = realpath('/var/www/uploads');
$requestedFile = realpath($baseDir . '/' . $userInput);
if ($requestedFile === false || !str_starts_with($requestedFile, $baseDir)) {
throw new SecurityException('Invalid file path');
}
Real-world example
A file download feature validates that a user requested file path, after being fully resolved, still falls within the intended uploads directory, blocking an attempted path traversal attack where a malicious user tried to include double dot sequences to access an unrelated system file.
Common follow-ups: What is the difference between blacklisting and whitelisting when it comes to validating file paths?;How does the realpath function help defend against path traversal attacks?
Security;File Upload Handling