Webエンジニア向けプログラミング解説動画をYouTubeで配信中!
▶ チャンネル登録はこちら

【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 を返します。

サンプルコード

PHPでファイルが読み込み可能か確認する

1<?php
2
3/**
4 * 指定されたファイルが読み込み可能かどうかをチェックし、その結果を出力する関数。
5 *
6 * is_readable 関数は、指定されたパスが存在し、かつ現在のスクリプトが
7 * そのファイルを読み込む権限を持っている場合に true を返します。
8 *
9 * @param string $filename チェックするファイルのパス。
10 * @return void
11 */
12function checkFileReadability(string $filename): void
13{
14    echo "--- Checking readability for: '{$filename}' ---" . PHP_EOL;
15
16    // is_readable 関数を使用してファイルの読み込み権限を確認します。
17    if (is_readable($filename)) {
18        echo "Result: The file '{$filename}' is readable." . PHP_EOL;
19    } else {
20        // キーワード「php file is not readable」に関連するシナリオ。
21        // ファイルが存在しないか、またはファイルへの読み込み権限がない場合にこのブロックが実行されます。
22        echo "Error: The file '{$filename}' is NOT readable. It might not exist, or its permissions are incorrect." . PHP_EOL;
23    }
24    echo PHP_EOL;
25}
26
27// --- サンプル実行 ---
28
29// 1. 存在しないファイルパスをチェックする例
30// このファイルは通常存在しないため、is_readable() は false を返し、
31// 「php file is not readable」の状態を示します。
32checkFileReadability('non_existent_example_file.txt');
33
34// 2. スクリプト自身(実行中のファイル)をチェックする例
35// このファイルは必ず存在し、スクリプトが実行されているため読み込み可能です。
36checkFileReadability(__FILE__);

PHPのis_readable関数は、指定されたファイルパスが現在のPHPスクリプトから読み込み可能であるかどうかを判定するために使用されます。引数には、読み込み可能かを確認したいファイルのパスを文字列で指定します。戻り値としては、ファイルが存在し、かつそのファイルを読み込む権限がある場合にtrue(真)を、それ以外の場合にはfalse(偽)をブール値で返します。

この関数は、例えばファイルを開いて内容を読み込む前に、その操作が成功するかどうかを事前に確認する際に役立ちます。サンプルコードのcheckFileReadability関数は、is_readableの具体的な挙動を示しています。

存在しないファイルパス(non_existent_example_file.txt)を指定した場合は、is_readablefalseを返し、「Error: The file is NOT readable.」と出力されます。これは「php file is not readable」という状況に該当し、ファイルが見つからないか、アクセス権限がないといった原因が考えられます。一方、__FILE__のように実行中のスクリプト自身のパスを指定すると、通常は読み込み可能であるためtrueが返され、「Result: The file is readable.」と表示されます。このように、ファイル操作の前にこの関数で確認することで、エラーを回避し、プログラムの安定性を向上させることができます。

is_readable関数は、指定されたファイルが存在し、かつ現在のスクリプトがそのファイルを読み込む権限を持っている場合にtrueを返します。ファイルが存在しないか、パーミッションが不十分な場合はfalseとなるため、適切なエラーメッセージで状況を伝えることが重要です。Webサーバー環境では、スクリプト実行ユーザー(例: www-data)の読み込み権限を確認してください。また、この関数がtrueを返した後でも、直後にファイルの状況が変わり、読み込みに失敗する可能性(競合状態)があります。そのため、実際にファイルを開く際には、予期せぬエラーに備えてエラーハンドリングを必ず実装しましょう。

PHP: is_readable()でファイル存在と読み取り権限を確認する

1<?php
2
3/**
4 * Demonstrates the use of the is_readable() function in PHP.
5 *
6 * This function checks if a file or directory exists and has read permissions.
7 * It's crucial for verifying access before attempting to read file contents,
8 * helping to prevent errors and ensure robust file operations.
9 */
10function demonstrateIsReadable(): void
11{
12    // Define a temporary file name for testing purposes.
13    $testFilename = 'example_test_file.txt';
14
15    echo "--- Testing is_readable() --- \n\n";
16
17    // --- Scenario 1: File exists and is readable ---
18    // Create the file and write some content to ensure it exists.
19    // file_put_contents() returns the number of bytes written, or false on failure.
20    if (file_put_contents($testFilename, "This is a test file for is_readable().") !== false) {
21        echo "Successfully created file: '{$testFilename}'\n";
22
23        // Check if the newly created file is readable.
24        if (is_readable($testFilename)) {
25            echo "Result for '{$testFilename}': It IS readable.\n";
26            // In a real application, you might now safely read the file, e.g.:
27            // echo "Content: " . file_get_contents($testFilename) . "\n";
28        } else {
29            echo "Result for '{$testFilename}': It IS NOT readable. (Unexpected for a newly created file)\n";
30        }
31
32        // Clean up: Remove the test file.
33        unlink($testFilename);
34        echo "Cleaned up file: '{$testFilename}'\n\n";
35    } else {
36        echo "Error: Could not create '{$testFilename}'. Check directory permissions.\n\n";
37    }
38
39    // --- Scenario 2: File does not exist ---
40    $nonExistentFilename = 'non_existent_file.txt';
41    echo "Checking non-existent file: '{$nonExistentFilename}'\n";
42
43    // Check if a file that definitely does not exist is readable.
44    if (is_readable($nonExistentFilename)) {
45        echo "Result for '{$nonExistentFilename}': It IS readable. (This should not happen)\n";
46    } else {
47        echo "Result for '{$nonExistentFilename}': It IS NOT readable. (Expected outcome)\n";
48    }
49
50    echo "\n--- End of demonstration --- \n";
51}
52
53// Call the function to run the demonstration.
54demonstrateIsReadable();
55
56?>

PHP 8のis_readable関数は、指定されたファイルやディレクトリが存在し、読み込み権限があるかを判定します。ファイルからのデータ読み込み前にこの関数で確認することで、エラーを回避し、プログラムの安定性を高めるために利用されます。

引数には、チェックしたいファイルまたはディレクトリのパスを文字列(string $filename)で渡します。戻り値は真偽値(bool)で、読み込み可能であればtrueを、ファイルが存在しない、または権限がないなどにより読み込み不可能であればfalseを返します。

サンプルコードでは、is_readableの二つの主要なケースを実演しています。まず、プログラム内で一時的なファイルを作成し、それがis_readableによって読み込み可能と判定されることを確認します。次に、実際には存在しないファイルを指定した場合にis_readablefalseを返すことを示しています。このように、ファイルへアクセスする前にis_readableで可否を確認する習慣は、安全で堅牢なファイル操作を実装するために非常に有効です。

is_readable()関数は、指定したファイルやディレクトリが存在し、PHPを実行しているユーザーが読み取り権限を持っているかを確認します。これにより、実際にファイルを読み込む前に「ファイルが見つからない」や「権限がない」といったエラーを回避し、プログラムを安定させることが可能です。

注意点として、is_readable()falseを返す場合、それはファイルが存在しないか、または読み取り権限がないかのどちらかであることを示します。ファイルが存在するかどうかだけを確認したい場合は、file_exists()関数の利用も検討しましょう。

また、PHPスクリプトはWebサーバーなどの実行ユーザーの権限で動作するため、ファイルの読み取り権限はそのユーザーに依存します。意図した動作にならない場合は、ファイルやディレクトリの権限設定を確認・調整してください。この関数のチェック後、実際にファイルアクセスを行うまでに状況が変わる可能性も考慮し、常にエラーハンドリングを組み合わせることが重要です。

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()などで適切にクリーンアップ処理を行うようにしてください。パーミッション設定によっては、削除前に権限を再度変更する必要がある点にも留意が必要です。

関連コンテンツ

関連プログラミング言語