PHP File Handling
PHP File Handling
Section titled “PHP File Handling”File handling is a crucial part of many web applications. PHP provides a comprehensive set of functions to create, read, write, and manage files on the server.
Important Security Note: Be extremely careful when working with files, especially when file paths or content involve user input. Improper handling can lead to serious security vulnerabilities (e.g., directory traversal, arbitrary file reading/writing) or data loss. Always validate and sanitize inputs, check file permissions, and avoid exposing sensitive file paths.
Simple File Reading and Writing
Section titled “Simple File Reading and Writing”For common tasks like reading the entire content of a file into a string or writing a string to a file, PHP offers convenient shortcut functions:
Reading a File (file_get_contents):
This function reads the entire file into a string. It’s very convenient for smaller files.
<?php$filename = 'data/dictionary.txt';
// Check if file exists and is readable before attempting to readif (file_exists($filename) && is_readable($filename)) { $content = file_get_contents($filename); if ($content === false) { echo "Error reading file."; } else { echo "<pre>" . htmlspecialchars($content) . "</pre>"; }} else { echo "File not found or not readable.";}?>Writing to a File (file_put_contents):
This function writes data (a string or an array) to a file. By default, it overwrites the file; use the FILE_APPEND flag to append.
<?php$filename = 'logs/app.log';$logMessage = date('Y-m-d H:i:s') . " - User action logged.\n";
// Attempt to append the message to the log file// file_put_contents creates the file if it doesn't exist$bytesWritten = file_put_contents($filename, $logMessage, FILE_APPEND | LOCK_EX);
if ($bytesWritten === false) { echo "Error writing to log file.";} else { echo "Log message added successfully ($bytesWritten bytes).";}?>Note the use of LOCK_EX for exclusive locking to prevent race conditions when multiple processes might write simultaneously.
Advanced File Handling (Using File Pointers)
Section titled “Advanced File Handling (Using File Pointers)”For more control, such as reading large files line by line or piece by piece, or working with binary data, use the traditional file pointer functions:
fopen(string $filename, string $mode): Opens a file or URL and returns a file pointer resource.fread(resource $handle, int $length): Reads up tolengthbytes from the file pointer.fgets(resource $handle, ?int $length = null): Gets a line from the file pointer.fwrite(resource $handle, string $string, ?int $length = null): Writes a string to the file pointer.fclose(resource $handle): Closes the file pointer.feof(resource $handle): Checks if the end-of-file has been reached.
Example: Reading a file line by line
<?php$filename = 'data/users.csv';$handle = @fopen($filename, 'r'); // Use 'r' for reading
if ($handle) { echo "<ul>"; while (($line = fgets($handle)) !== false) { // Process each line (e.g., parse CSV, display) echo "<li>" . htmlspecialchars(trim($line)) . "</li>"; } echo "</ul>";
if (!feof($handle)) { echo "Error: unexpected fgets() fail."; }
fclose($handle);} else { echo "Could not open file: $filename";}?>Using @fopen suppresses errors if the file can’t be opened, which is why the if ($handle) check is essential immediately after.
Other Useful File Functions
Section titled “Other Useful File Functions”file_exists(string $filename): Checks whether a file or directory exists.is_readable(string $filename): Checks if a file exists and is readable.is_writable(string $filename): Checks if a file exists and is writable.is_dir(string $filename): Checks if the filename is a directory.is_file(string $filename): Checks if the filename is a regular file.filesize(string $filename): Gets the file size in bytes.unlink(string $filename): Deletes a file.mkdir(string $pathname, int $mode = 0777, bool $recursive = false): Creates a directory.rmdir(string $dirname): Removes an empty directory.copy(string $source, string $dest): Copies a file.rename(string $oldname, string $newname): Renames or moves a file or directory.
Always consult the official PHP documentation for detailed usage, parameters, return values, and potential error conditions for these functions.