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

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

作成日: 更新日:

基本的な使い方

lstat関数は、指定されたファイルやディレクトリのメタデータ(属性情報)を取得する関数です。この関数は、ファイルサイズ、最終アクセス時刻、最終変更時刻、最終状態変更時刻、ファイルの所有者ID、グループID、ファイルのパーミッション、デバイスIDなど、ファイルシステムに関する詳細な情報を配列として返します。情報を取得したいファイルやディレクトリのパスを引数として指定し、成功した場合はこれらの情報を含む連想配列を返します。パスが存在しない、あるいはアクセス権がないなどの理由で情報の取得に失敗した場合はfalseを返します。

この関数の大きな特徴は、シンボリックリンク(別のファイルやディレクトリを指し示す特殊なファイル)に対して実行された場合です。lstat関数は、シンボリックリンクが指し示す先のファイルではなく、シンボリックリンクファイル自体の属性情報を返します。例えば、シンボリックリンクファイル自身のサイズ、最終更新時刻、パーミッションなどを確認したい場合にこの関数が利用されます。これは、stat()関数がシンボリックリンクの指す先のファイル情報を取得するのとは異なる挙動であり、シンボリックリンク自体の管理や、リンクファイルの状態を正確に把握する必要があるシステム管理のシナリオで特に重要となります。ファイルシステムの整合性を確認したり、特定のファイルタイプ(シンボリックリンク)の状態を詳細に調査したりする際に活用される、PHPにおけるファイル操作の基本的な関数の一つです。

構文(syntax)

1lstat('/path/to/your/file_or_symlink');

引数(parameters)

string $filename

  • string $filename: 統計情報を取得したいファイルまたはシンボリックリンクのパスを指定する文字列

戻り値(return)

array|false

lstat関数は、指定されたファイルのステータス情報を配列として返します。エラーが発生した場合はfalseを返します。

サンプルコード

PHP 8 lstat() の使い方と失敗時の処理

1<?php
2
3/**
4 * Demonstrates the usage of the lstat() function in PHP 8.
5 *
6 * This function creates a temporary file and a symbolic link to it,
7 * then uses lstat() to retrieve information about both. It highlights
8 * lstat()'s specific behavior for symbolic links (reporting on the link itself)
9 * and shows how to handle cases where lstat() fails, such as for
10 * non-existent paths. It also incorporates the filetype() function for comparison.
11 */
12function demonstrateLstat(): void
13{
14    // Define paths for a temporary file, a symbolic link, and a non-existent path
15    $tempFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'php_lstat_test_file_' . uniqid() . '.txt';
16    $symlinkPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'php_lstat_test_link_' . uniqid() . '.txt';
17    $nonExistentPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'non_existent_file_' . uniqid() . '.txt';
18
19    echo "--- Preparing Demonstration ---\n";
20
21    // 1. Create a temporary file with some content
22    if (file_put_contents($tempFilePath, 'This is a test file for lstat demonstration.') === false) {
23        echo "Error: Could not create temporary file: {$tempFilePath}\n";
24        return;
25    }
26    echo "Successfully created temporary file: {$tempFilePath}\n";
27
28    // 2. Create a symbolic link pointing to the temporary file
29    // Note: Symbolic link creation might require specific permissions on some systems.
30    if (!symlink($tempFilePath, $symlinkPath)) {
31        echo "Error: Could not create symbolic link from {$symlinkPath} to {$tempFilePath}\n";
32        unlink($tempFilePath); // Clean up the original file if link creation fails
33        return;
34    }
35    echo "Successfully created symbolic link: {$symlinkPath} pointing to {$tempFilePath}\n";
36
37    echo "\n--- lstat() on the Original File ---\n";
38    // lstat() on a regular file behaves like stat(), returning information about the file itself.
39    $statsFile = lstat($tempFilePath);
40    if ($statsFile === false) {
41        echo "lstat() failed for original file: {$tempFilePath}\n";
42    } else {
43        echo "Path: {$tempFilePath}\n";
44        echo "  Reported file type (from filetype() function): " . filetype($tempFilePath) . "\n";
45        // Interpret the 'mode' field from lstat() to check if it's a regular file (0x8000 for S_IFREG)
46        echo "  Is regular file (from lstat() mode bitmask): " . ((($statsFile['mode'] & 0xF000) === 0x8000) ? 'Yes' : 'No') . "\n";
47        echo "  Size: {$statsFile['size']} bytes\n";
48    }
49
50    echo "\n--- lstat() on the Symbolic Link ---\n";
51    // lstat() on a symbolic link returns information about the *link itself*, not its target.
52    $statsLink = lstat($symlinkPath);
53    if ($statsLink === false) {
54        echo "lstat() failed for symbolic link: {$symlinkPath}\n";
55    } else {
56        echo "Path: {$symlinkPath}\n";
57        echo "  Reported file type (from filetype() function): " . filetype($symlinkPath) . "\n"; // This will typically report 'link'
58        // Interpret the 'mode' field from lstat() to check if it's a symbolic link (0xA000 for S_IFLNK)
59        echo "  Is symbolic link (from lstat() mode bitmask): " . ((($statsLink['mode'] & 0xF000) === 0xA000) ? 'Yes' : 'No') . "\n";
60        // The size for a symbolic link typically refers to the length of the path it points to.
61        echo "  Size (of the link itself): {$statsLink['size']} bytes\n";
62    }
63
64    echo "\n--- lstat() on a Non-Existent Path (Demonstrates Failure) ---\n";
65    // lstat() returns false if the file or link does not exist.
66    // We use '@' to suppress PHP warnings for a clean output in this demonstration.
67    $statsNonExistent = @lstat($nonExistentPath);
68    if ($statsNonExistent === false) {
69        echo "lstat() failed for non-existent path: {$nonExistentPath} as expected.\n";
70        // Use error_get_last() to retrieve the specific warning/error message.
71        $lastError = error_get_last();
72        if ($lastError && $lastError['type'] === E_WARNING) {
73            echo "  Details (last warning): " . $lastError['message'] . "\n";
74        }
75    } else {
76        echo "Unexpected: lstat() returned data for a non-existent path.\n";
77    }
78
79    echo "\n--- Cleaning Up ---\n";
80    // Clean up the created files and links
81    if (file_exists($symlinkPath) && !unlink($symlinkPath)) {
82        echo "Warning: Could not delete symbolic link: {$symlinkPath}\n";
83    } elseif (file_exists($symlinkPath)) {
84        echo "Deleted symbolic link: {$symlinkPath}\n";
85    } else {
86        echo "Symbolic link already removed or never created: {$symlinkPath}\n";
87    }
88
89    if (file_exists($tempFilePath) && !unlink($tempFilePath)) {
90        echo "Warning: Could not delete temporary file: {$tempFilePath}\n";
91    } elseif (file_exists($tempFilePath)) {
92        echo "Deleted temporary file: {$tempFilePath}\n";
93    } else {
94        echo "Temporary file already removed or never created: {$tempFilePath}\n";
95    }
96
97    echo "\nDemonstration complete.\n";
98}
99
100// Execute the demonstration function
101demonstrateLstat();

lstat()は、PHPでファイルやディレクトリの情報を取得するための関数です。引数には情報を取得したいパス($filename)を指定します。成功すると、ファイルの詳細な情報を含む配列を返しますが、指定されたパスが存在しないなどの理由で情報取得に失敗した場合はfalseを返します。

この関数は、通常のファイルに対してはstat()関数と同様に動作し、ファイルそのものの情報(サイズ、更新日時など)を返します。stat()関数と異なる重要な点は、シンボリックリンクが指定された場合の挙動です。lstat()は、リンク先のファイルではなく、シンボリックリンクそれ自体の情報を返します。例えば、filetype()関数で調べると「link」と報告されます。これは、たとえリンクが指すファイルが存在しなくても、シンボリックリンク自体が存在すればその情報を取得できることを意味します。

サンプルコードでは、一時ファイルとそれへのシンボリックリンクを作成し、それぞれのパスに対してlstat()を適用することで、この挙動の違いを具体的に示しています。特に、シンボリックリンクに対してlstat()を使うと、そのリンク自体の特性(リンクであること、リンクパスの長さなど)が得られることが分かります。また、存在しないパスにlstat()を使用した場合に「lstat failed for」というメッセージとともにfalseが返される失敗例も確認でき、戻り値を確認してエラー処理を行う重要性を示しています。

lstat()関数は、シンボリックリンクに対してはリンクそのものの情報を返し、リンク先の情報は取得しません。リンク先の情報を知るにはstat()関数を使用してください。この関数は成功時に配列を、失敗時にfalseを返しますので、必ずfalseチェックによるエラー処理を実装することが重要です。存在しないファイルやシンボリックリンクに対して実行した場合もfalseを返し、PHPの警告が発生することがあります。警告は@演算子で抑制できますが、error_get_last()でエラー詳細を確認し、堅牢な処理を心がけましょう。サンプルコードで生成される一時ファイルやリンクは、処理後に確実に削除し、リソースリークを防いでください。シンボリックリンク作成にはシステムによって特定の権限が必要な場合もあります。

関連コンテンツ