LoginSignup
4
2

More than 3 years have passed since last update.

【PHP】大量のファイルがあるディレクトリ内から高速にファイルのパスを取得する

Last updated at Posted at 2019-05-31

コード

Linux 環境であれば、exec()find コマンドとを組み合わせるだけです。

$pathAry = [];
exec('find /path/to/dir -type f', $pathAry);

print_r($pathAry);

exec('find ...', $array); とすると、$array で結果を配列で受け取れる辺り、いかにも PHP らしいと思います。


実用例

以下は、大量のファイルがあるディレクトリ内から、.htaccess ファイルを探し出し、その中身をファイルに書き出す例です。

find_htaccess.php
#!/usr/local/bin/php
<?php
//-- findコマンドの設定
$findAry = [
    'find' => '/path/to/dir',    // 検索対象ディレクトリ
    '-maxdepth' => '4',          // ディレクトリを掘る深さ
    '-type' => 'f',              // ファイルのみを対象とする
    '-name' => '.htaccess',      // 検索対象ファイル名
];

//-- 実行結果保存ファイル
$resultPath = __FILE__ . '.result.txt';

//-- 実行結果保存ファイルの作成
if (is_file($resultPath)) {
    file_put_contents($resultPath, '');
} else {
    touch($resultPath);
}

//-- findコマンドを生成
$command = '';

foreach (array_map('escapeshellarg', $findAry) as $opt => $val) {
    $command .= "{$opt} {$val} ";
}

//-- findを実行しその結果を受け取る
$pathAry = [];
exec($command, $pathAry);

//-- 見つかったファイルの中身をファイルへ書き出す
foreach ($pathAry as $path) {
    file_put_contents(
        $resultPath,
        "▼{$path}\n" . file_get_contents($path) . "\n\n" . str_repeat('-', 60) . "\n\n",
        FILE_APPEND | LOCK_EX
    );
}

使い方

$ chmod +x ./find_htaccess.php && ./find_htaccess.php

これ、PHP で書く必要ある?とか野暮な事は言わないよう(笑)


余談

PHP から指定ディレクトリ内のファイルパスを取得する方法について、軽くググってみると…

  • glob()
  • scandir()
  • opendir()readdir()

…について書いてある記事が大半で、DirectoryIterator に触れている記事すらあまり無いようです。

Linux 環境なら exec()find コマンドとを組み合わせるだけですので、簡単な検索条件なら glob() 並の手軽さだと思います。しかも、glob() よりも遥かに高速です。(上記 4 つの中では glob() が最も遅い筈。)

もちろん、find コマンドを極めれば、もっと複雑な条件でも検索が可能ですが、記事の趣旨からそれるため、ググった結果でお茶を濁しておきます。

4
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2