Check if a File is Readable or Writable in PHP

Before attempting to read from or write to a file in PHP, it is crucial to verify its permissions to prevent runtime errors and application crashes. This article provides a straightforward guide on how to use PHP’s built-in functions, is_readable() and is_writable(), to check file accessibility safely and efficiently before performing any file operations.

Checking if a File is Readable

To check if a file exists and is readable by your PHP script, use the is_readable() function. This function takes the file path as an argument and returns true if the file exists and can be read, and false otherwise.

$filename = 'data.txt';

if (is_readable($filename)) {
    $content = file_get_contents($filename);
    echo "File content read successfully.";
} else {
    echo "The file is not readable or does not exist.";
}

Checking if a File is Writable

To determine whether you can write data to a file, use the is_writable() function. This function returns true if the file exists and is writable. If the file does not exist yet but the parent directory is writable (meaning you can create the file), it will also return true.

$filename = 'data.txt';

if (is_writable($filename)) {
    file_put_contents($filename, "New data string");
    echo "File written successfully.";
} else {
    echo "The file is not writable.";
}

Combining Checks for Complete File Handling

In many real-world scenarios, you need to read a file, modify its contents, and then write it back. You can combine both functions to ensure safe file manipulation.

$filename = 'config.json';

if (file_exists($filename)) {
    if (is_readable($filename) && is_writable($filename)) {
        // Safe to read and write
        $data = json_decode(file_get_contents($filename), true);
        $data['last_updated'] = time();
        file_put_contents($filename, json_encode($data));
        echo "Configuration updated successfully.";
    } else {
        echo "Error: File permissions do not allow read/write operations.";
    }
} else {
    echo "Error: File does not exist.";
}