Current Location: Home> Latest Articles> Combining is_readable and file_get_contents to determine whether the file is readable

Combining is_readable and file_get_contents to determine whether the file is readable

gitbox 2025-06-03

In PHP, operating files is a common requirement, and ensuring that files can be read safely is a key step to avoid program errors and security risks. This article will introduce how to combine the is_readable function and the file_get_contents function to determine whether a file can be read safely.


1. Introduction to is_readable function

is_readable is a built-in function of PHP that checks whether a specified file or directory has readable permissions. Its syntax is very simple:

 is_readable(string $filename): bool
  • The return value is a Boolean value, true means that the file exists and is readable, and false means that the file is unreadable or does not exist.

Using is_readable can prevent the program from trying to read a file that does not exist or does not have permission to read, thereby reducing errors.


2. Introduction to file_get_contents function

file_get_contents is used to read file contents and is a simple and convenient way to read small files.

 file_get_contents(string $filename): string|false
  • Returns the file content string, if it fails, returns false .

However, when file_get_contents is read, if the file does not exist or has insufficient permissions, it will return false and generate a warning. Combining is_readable can avoid this warning.


3. Combination use examples

The following code example shows how to use is_readable to determine whether a file is readable, and then use file_get_contents to safely read the file content.

 <?php
$file = "gitbox.net/path/to/yourfile.txt";

if (is_readable($file)) {
    $content = file_get_contents($file);
    if ($content !== false) {
        echo "The file content is as follows:\n";
        echo $content;
    } else {
        echo "An error occurred while reading a file。";
    }
} else {
    echo "The file is unreadable or does not exist。";
}
?>

4. Instructions and precautions

  • Permissions issue : Even if the file exists, operating system permissions may make the file unreadable. is_readable can help us check permissions in advance.

  • File path security : Ensure file paths are controlled and prevent directory traversal attacks.

  • Large file processing : file_get_contents is suitable for reading smaller files. It is recommended to use streaming reading for large files.

  • Network file : If the file path is a URL, make sure to allow_url_fopen is allowed, otherwise you cannot read it with file_get_contents .


Through the above methods, we can read files safely and efficiently, avoiding program crashes or leaking sensitive information.