0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPで特定のディレクトリ内のファイルを取得する方法

Posted at

写真を複数枚表示したい時に、
DBに保存する程の枚数じゃないけど、一つ一つ表示するコードを書くと面倒だったので、
写真だけが入ったimageフォルダから写真のファイル名を取得して配列にする関数を作った。

function get_file_name($dir){
// ディレクトリの存在確認&ハンドルの取得
    if(is_dir($dir) && $handle = opendir($dir)){
    
        $files = array();
        // ループ処理(ディレクトリを読み込んでエントリがfalseでない間)
        while(($file = readdir($handle)) !== false){
            // ファイルタイプがfileの場合のみ処理する(ディレクトリとかでない場合)
            if(filetype($path = $dir.$file) == "file"){
                array_push($files,$path);
            }
        }
        return $files;
    }
}

(参考)
コード:https://syncer.jp/php-how-to-get-directory-file-list
opendir():http://php.net/manual/ja/function.opendir.php
readdir():http://php.net/manual/ja/function.readdir.php
filetype():http://php.net/manual/ja/function.filetype.php
array_push():http://php.net/manual/ja/function.array-push.php
is_dir():http://php.net/manual/ja/function.is-dir.php

0
2
1

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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?