2021/06/30
PHP 最強に簡単なファイル一覧取得方法
PHPで指定したディレクトリからファイルの一覧を取得する方法です。
個人的に一番分かりやすく取得しやすい方法だと思います。
ではさっそく見ていきましょう。
「scandir」という関数を使用します。
$file_list = scandir('./path/to');
第一引数にファイル一覧が欲しいディレクトリを指定するだけです。
これだけで取得が行えます。
WordPressが入っているディレクトリを指定して、$file_listをvar_dumpして中身を見ると….
array(24) {
[0]=>
string(1) "."
[1]=>
string(2) ".."
[2]=>
string(10) "wp-content"
[3]=>
string(17) "wp-links-opml.php"
[4]=>
string(11) "wp-load.php"
[5]=>
string(18) "wp-blog-header.php"
[6]=>
string(11) "license.txt"
[7]=>
string(9) "index.php"
[8]=>
string(11) "wp-mail.php"
[9]=>
string(13) "wp-signup.php"
[10]=>
string(15) "wp-activate.php"
[11]=>
string(11) "wp-cron.php"
[12]=>
string(16) "wp-trackback.php"
[13]=>
string(10) "xmlrpc.php"
[14]=>
string(20) "wp-comments-post.php"
[15]=>
string(20) "wp-config-sample.php"
[16]=>
string(15) "wp-settings.php"
[17]=>
string(12) "wp-login.php"
[18]=>
string(11) "readme.html"
[19]=>
string(13) "wp-config.php"
[20]=>
string(8) "wp-admin"
[21]=>
string(11) "wp-includes"
[22]=>
string(9) ".htaccess"
}
ちゃんと取得が行えています。
ただ、「.」と「..」も含まれています。
これを無くしたもので取得するには下記の様にします。
$file_list = array_diff( scandir('./path/to'), array('.', '..') );
array_diffの第二引数で必要ないものを削除して取得するといった感じになります。
ちなみに、このままだとディレクトリとファイルの両方の一覧を取得する形になる為、ファイルのみ欲しい場合はforeachで回して判定する必要があります。
$file_list = array_diff( scandir('./path/to'), array('.', '..') );
foreach( $file_list as $file ) {
if ( is_file( $file ) ) {
// ファイルの場合
} elseif ( is_dir( $file ) ) {
// ディレクトリの場合
}
}
以上になります。
一番簡単で欲しい内容が取れる最強の方法だと思います。(あくまで簡単な方法です!)
拡張子が○○のものだけ取得したい場合といったものになると「glob」という関数が非常に便利です。
こちらに関しては下記リンクを参照して下さい!
https://qiita.com/katsukii/items/ec816b23f68b6dfa0f87
ちなみに、scandirの並び順を変える、第二引数が存在するので気になる方は下記リンクをご参照ください。