PHP is_readable: Check File Accessibility

The PHP is_readable function is an essential tool that helps you validate file readability before attempting operations like reading or including files. In this guide, we will explore how is_readable works, its syntax, and how to use it. So let’s get started.

What Is PHP is_readable?

The is_readable function checks if a given file or directory exists and whether it can be read. It is a built-in PHP function that returns a boolean value—true if the file is readable and false otherwise.

Here is its syntax:

is_readable(string $filename)
  • Parameter: $filename is the file or directory path you want to check.
  • Return Value: The function returns true if the specified file or directory exists and is readable; otherwise, it returns false.

For example:

$file = 'example.txt';

if (is_readable($file)) {
    echo "File is readable.";
} else {
    echo "File cannot be read.";
}

The example above shows that is_readable validates if example.txt is readable. This simple check guarantees that your application will not suffer any surprising errors. Similarly, in the following part:

In the next section, we will see more examples for is_readable.

Examples of PHP is_readable

Validating a File Before Reading

Suppose you want to read a configuration file. Before doing that, you can check if it is readable:

$configFile = 'config.json';

if (is_readable($configFile)) {
    $content = file_get_contents($configFile);
    echo "Configuration loaded successfully.";
} else {
    echo "Cannot access the configuration file.";
}

This ensures your script doesn’t crash if the file is missing or inaccessible.

Ensuring Dynamic Includes Work

When your application dynamically includes files, is_readable verifies the file’s existence and readability:

$fileToInclude = 'plugin.php';

if (is_readable($fileToInclude)) {
    include $fileToInclude;
} else {
    echo "Plugin file not found.";
}

Handling Directory Readability

You have to know that the function is not limited to files—it also works with directories. For example: Here is a check if a directory is accessible before listing its contents:

$directory = 'uploads';

if (is_readable($directory)) {
    echo "Directory is accessible.";
} else {
    echo "Directory cannot be read.";
}

Let’s summarize it.

Wrapping It Up

The PHP is_readable function is a way to ensure file and directory accessibility in your applications. By checking readability before performing operations, you can prevent errors, improve security, and provide a smoother user experience.

    Previous Article

    PHP file_exists: Check File and Directory Existence

    Next Article

    PHP is_file Function: Check if a File Exists

    Write a Comment

    Leave a Comment

    Your email address will not be published. Required fields are marked *

    Subscribe to Get Updates

    Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
    No spam. Unsubscribe anytime.