【PHP8.x】is_readable関数の使い方

is_readable関数の使い方について、初心者にもわかりやすく解説します。

作成日: 更新日:

基本的な使い方

is_readable関数は、指定されたファイルまたはディレクトリが現在のPHPスクリプトから読み込み可能であるかを確認する関数です。この関数は、プログラムが特定のファイルの内容を読み取ったり、ディレクトリ内の情報を取得したりする前に、その操作が実際に可能であるかを判断するために使用されます。

引数として、確認したいファイルまたはディレクトリへのパスを文字列で指定します。指定されたパスが読み込み可能であると判断されればブール値のtrueを返し、読み込み不可能であればfalseを返します。「読み込み可能」とは、単にファイルやディレクトリが存在するだけでなく、PHPスクリプトを実行しているサーバーユーザーが、その対象に対する読み込み権限を適切に持っている状態を意味します。

ファイル操作を行うアプリケーションを開発する際には、file_get_contents()などの実際のファイル読み込み処理を実行する前にis_readable()で権限を事前にチェックすることが非常に有効です。これにより、存在しないファイルや権限のないファイルへのアクセス試行によるエラーや警告を未然に防ぎ、より堅牢で安定したプログラムを構築することができます。ファイルが存在するかどうかだけを確認したい場合はfile_exists()関数も利用できますが、is_readable()は存在確認に加えて、実質的な読み込み権限の有無まで確認する点で異なります。この関数はPHP 8環境で利用可能です。

構文(syntax)

1<?php
2$filepath = 'path/to/your/file.txt'; // 読み込み可能か確認したいファイルのパス
3$isReadable = is_readable($filepath); // ファイルが読み込み可能であれば true、そうでなければ false を返す
4?>

引数(parameters)

string $filename

  • string $filename: 読み込み可能かどうかを確認したいファイルパスを指定する文字列

戻り値(return)

bool

指定されたファイルパスのファイルまたはディレクトリが読み取り可能である場合に true を、そうでない場合に false を返します。

サンプルコード

is_readable() が false を返す場合

1<?php
2
3/**
4 * is_readable() 関数の使用例です。
5 * 指定されたファイルが存在しない、または読み取り権限がない場合に
6 * is_readable() が `false` を返すケースを示します。
7 */
8
9// 存在しないファイルのパスを指定します。
10// このファイルはシステム上に存在しないことを前提とします。
11$nonExistentFilePath = 'sample_non_existent_file.txt';
12
13// is_readable() 関数を呼び出し、ファイルの読み込み可能性をチェックします。
14if (is_readable($nonExistentFilePath)) {
15    // このブロックは、ファイルが存在し、かつ読み込み可能である場合に実行されます。
16    // 今回の例では、ファイルが存在しないため通常は実行されません。
17    echo "ファイル '{$nonExistentFilePath}' は読み込み可能です。\n";
18} else {
19    // is_readable() が false を返した場合に実行されます。
20    // これは、ファイルが存在しないか、スクリプトにファイルを読み取る権限がないことを意味します。
21    echo "ファイル '{$nonExistentFilePath}' は読み込みできません。\n";
22    echo "理由:ファイルが存在しないか、読み取り権限がありません。\n";
23}
24
25?>

is_readable関数は、指定したファイルが「読み取り可能かどうか」をチェックするPHPの関数です。この関数は、引数として確認したいファイルのパスを文字列で受け取ります。そして、ファイルの読み込みが可能であれば真偽値のtrueを、読み込みが不可能であればfalseを戻り値として返します。

このサンプルコードでは、sample_non_existent_file.txtという「存在しないファイル」のパスを指定してis_readable関数を呼び出しています。is_readable関数は、対象のファイルが存在しない場合や、PHPを実行しているスクリプトにそのファイルを読み取る権限がない場合にfalseを返します。そのため、このコードを実行するとis_readable($nonExistentFilePath)falseと評価され、elseブロック内の「ファイル 'sample_non_existent_file.txt' は読み込みできません。理由:ファイルが存在しないか、読み取り権限がありません。」というメッセージが表示されます。

このように、ファイル操作を行う前にis_readable関数で読み取り可能性を事前に確認することは非常に重要です。これにより、ファイルが見つからない、またはアクセス権限がないといった理由で発生するエラーを未然に防ぎ、安全で信頼性の高いプログラムを作成することができます。

is_readable()関数は、指定されたファイルが「存在し、かつ、PHPスクリプトを実行しているユーザーに読み取り権限がある」場合にのみtrueを返します。サンプルコードのようにfalseが返る場合、ファイルが存在しないか、PHP実行ユーザーに読み取り権限がないかのどちらか、または両方が原因です。初心者は、ファイルが存在するだけではtrueにならない点に特に注意してください。システムで利用する際は、PHPスクリプトの実行ユーザー(Webサーバーユーザーなど)の権限設定を必ず確認し、安全にファイルを扱えるようにすることが重要です。falseの具体的な原因を特定するには、file_exists()と組み合わせるなど、追加のチェックやログ出力が役立ちます。

PHP: is_readable()file_exists() の違いを理解する

1<?php
2
3declare(strict_types=1);
4
5/**
6 * Demonstrates the difference between file_exists() and is_readable() functions.
7 *
8 * `file_exists()` checks if a file or directory exists at the specified path.
9 * `is_readable()` checks if a file or directory exists AND if its contents can be read by the current script.
10 * This distinction is crucial for securely handling files and preventing runtime errors.
11 */
12function demonstrateFilePermissionsChecks(): void
13{
14    // Define temporary file paths to ensure the example is self-contained and clean.
15    $tempDir = sys_get_temp_dir();
16    $readableFilePath = $tempDir . DIRECTORY_SEPARATOR . 'test_readable_file.txt';
17    $unreadableFilePath = $tempDir . DIRECTORY_SEPARATOR . 'test_unreadable_file.txt';
18    $nonExistentFilePath = $tempDir . DIRECTORY_SEPARATOR . 'test_non_existent_file.txt';
19
20    echo "--- Preparing Test Files ---\n";
21
22    // Scenario 1: Create a file that exists and is readable by the script.
23    // Default file permissions often allow the owner (the script's user) to read.
24    if (file_put_contents($readableFilePath, 'Content for a readable file.') !== false) {
25        // Ensure standard readable permissions (e.g., owner read/write, group read, others read).
26        chmod($readableFilePath, 0644);
27        echo "Created readable file: " . basename($readableFilePath) . "\n";
28    } else {
29        echo "ERROR: Failed to create readable file: " . basename($readableFilePath) . "\n";
30        return; // Exit if essential setup fails.
31    }
32
33    // Scenario 2: Create a file that exists but is NOT readable by the script.
34    // Setting permissions to 0000 means no user (owner, group, or others) has any access.
35    if (file_put_contents($unreadableFilePath, 'Content for an unreadable file.') !== false) {
36        chmod($unreadableFilePath, 0000); // No permissions for anyone.
37        echo "Created unreadable file: " . basename($unreadableFilePath) . " (permissions set to 0000)\n";
38    } else {
39        echo "ERROR: Failed to create unreadable file: " . basename($unreadableFilePath) . "\n";
40        // Clean up the previously created file if this step fails.
41        @unlink($readableFilePath);
42        return;
43    }
44
45    echo "\n--- Running Checks ---\n";
46
47    // Test Case 1: File exists and is readable.
48    echo "\nTesting file: " . basename($readableFilePath) . " (Expected: exists=true, readable=true)\n";
49    echo "  file_exists(): " . (file_exists($readableFilePath) ? 'true' : 'false') . "\n";
50    echo "  is_readable(): " . (is_readable($readableFilePath) ? 'true' : 'false') . "\n";
51
52    // Test Case 2: File exists but is NOT readable by the script.
53    // This highlights the key difference: file_exists() will be true, but is_readable() will be false.
54    echo "\nTesting file: " . basename($unreadableFilePath) . " (Expected: exists=true, readable=false)\n";
55    echo "  file_exists(): " . (file_exists($unreadableFilePath) ? 'true' : 'false') . "\n";
56    echo "  is_readable(): " . (is_readable($unreadableFilePath) ? 'true' : 'false') . "\n";
57
58    // Test Case 3: File does not exist.
59    echo "\nTesting file: " . basename($nonExistentFilePath) . " (Expected: exists=false, readable=false)\n";
60    echo "  file_exists(): " . (file_exists($nonExistentFilePath) ? 'true' : 'false') . "\n";
61    echo "  is_readable(): " . (is_readable($nonExistentFilePath) ? 'true' : 'false') . "\n";
62
63    echo "\n--- Cleaning Up Temporary Files ---\n";
64    // Clean up the created temporary files. '@' suppresses errors if files are already gone.
65    if (file_exists($readableFilePath)) {
66        @unlink($readableFilePath);
67        echo "Deleted " . basename($readableFilePath) . "\n";
68    }
69    if (file_exists($unreadableFilePath)) {
70        // IMPORTANT: To delete a file with 0000 permissions, its permissions must first be
71        // changed to allow the script to modify/delete it.
72        chmod($unreadableFilePath, 0644);
73        @unlink($unreadableFilePath);
74        echo "Deleted " . basename($unreadableFilePath) . "\n";
75    }
76    echo "Cleanup complete.\n";
77}
78
79// Execute the demonstration function.
80demonstrateFilePermissionsChecks();

PHP 8 の is_readable 関数は、指定されたファイルやディレクトリが「存在し、かつ現在のPHPスクリプトによって読み取り可能であるか」を真偽値で判定します。引数 string $filename にはチェックしたいファイルやディレクトリのパスを文字列で指定し、戻り値は読み取り可能であれば true、そうでなければ false を返します。

この関数は、単にファイルが存在するかを調べる file_exists 関数と混同されがちですが、重要な違いがあります。file_exists がパスにファイルやディレクトリがあるかだけを確認するのに対し、is_readable はそれに加えて、スクリプトがその内容にアクセスする権限を持っているかをチェックします。

提供されたサンプルコードは、この違いを明確に示しています。まず、読み取り可能なファイルと、パーミッションを0000に設定して意図的に読み取り不可能にしたファイルを一時的に作成します。読み取り可能なファイルに対しては、file_existsis_readabletrue を返します。しかし、読み取り不可能にしたファイルに対しては、file_existstrue を返す一方で、is_readablefalse を返します。これは、ファイル自体は存在しても、スクリプトがその内容を読み取る権限がないためです。存在しないファイルに対しては、両関数ともに false を返します。

このように、ファイルが存在するだけでなく、実際に読み取って処理できるかどうかを確認することは、ファイル操作を行うアプリケーションでエラーを防ぎ、予期せぬ動作を避ける上で非常に重要です。

このサンプルコードは、file_exists()is_readable()関数の決定的な違いを明確に示しています。is_readable()は、指定されたファイルが存在するだけでなく、現在のPHPスクリプトがそのファイルを読み取る権限を持っているかを確認します。これにより、ファイルが存在しても権限不足でアクセスできない場合に発生するエラーを未然に防ぎ、より堅牢なファイル処理を実現します。

特に、外部からの入力をファイルパスとして扱う場合、is_readable()を使用して読み込み権限を事前に確認することは、セキュリティ上のリスクを軽減し、不正なファイルアクセスを防ぐ上で非常に重要です。また、サンプルコードのように一時ファイルを生成しパーミッションを変更する際は、必ず使用後にunlink()などで適切にクリーンアップ処理を行うようにしてください。パーミッション設定によっては、削除前に権限を再度変更する必要がある点にも留意が必要です。

関連コンテンツ

【PHP8.x】is_readable関数の使い方 | いっしー@Webエンジニア