programing

PHP가 있는 디렉터리의 모든 파일 이름 가져오기

bestcode 2022. 9. 25. 00:28
반응형

PHP가 있는 디렉터리의 모든 파일 이름 가져오기

어떤 이유에서인지 다음 코드의 파일 이름에 '1'이 계속 표시됩니다.

if (is_dir($log_directory))
{
    if ($handle = opendir($log_directory))
    {
        while($file = readdir($handle) !== FALSE)
        {
            $results_array[] = $file;
        }
        closedir($handle);
    }
}

$results_array의 각 요소를 에코하면 파일 이름이 아닌 '1'이 많이 표시됩니다.파일 이름은 어떻게 알 수 있나요?

오픈/읽기 번거로움 없이 대신 사용:

foreach(glob($log_directory.'/*.*') as $file) {
    ...
}

SPL 스타일:

foreach (new DirectoryIterator(__DIR__) as $file) {
  if ($file->isFile()) {
      print $file->getFilename() . "\n";
  }
}

디렉토리 확인사용할 수 있는 메서드 목록에 대한 반복기 및 SplFileInfo 클래스.

접수된 답변에는 두 가지 중요한 단점이 있기 때문에, 정답을 찾고 있는 새로운 고객을 위해 개선된 답변을 게시합니다.

foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
    // Do something with $file
}
  1. 필터링globe함수 결과is_file일부 디렉토리가 반환될 수 있기 때문에 필요합니다.
  2. 모든 파일에 다음 파일이 있는 것은 아닙니다..그들의 이름으로, 그래서*/*패턴은 일반적으로 구리다.

주위를 둘러보셔야 합니다.$file = readdir($handle)괄호로 묶어서

여기 있습니다.

$log_directory = 'your_dir_name_here';

$results_array = array();

if (is_dir($log_directory))
{
        if ($handle = opendir($log_directory))
        {
                //Notice the parentheses I added:
                while(($file = readdir($handle)) !== FALSE)
                {
                        $results_array[] = $file;
                }
                closedir($handle);
        }
}

//Output findings
foreach($results_array as $value)
{
    echo $value . '<br />';
}

그냥 사용하다glob('*')여기 매뉴얼이 있습니다.

이 작업을 수행하기 위한 더 작은 코드가 있습니다.

$path = "Pending2Post/";
$files = scandir($path);
foreach ($files as &$value) {
    echo "<a href='http://localhost/".$value."' target='_blank' >".$value."</a><br/><br/>";
}

OS에 따라서는. ..그리고..DS_Store사용할 수 없기 때문에 숨깁시다.

먼저 파일에 대한 모든 정보를 가져옵니다.scandir()

// Folder where you want to get all files names from
$dir = "uploads/";

/* Hide this */
$hideName = array('.','..','.DS_Store');    

// Sort in ascending order - this is default
$files = scandir($dir);
/* While this to there no more files are */
foreach($files as $filename) {
    if(!in_array($filename, $hideName)){
       /* echo the name of the files */
       echo "$filename<br>";
    }
}

오퍼레이터의 신중함 때문입니다.다음 항목으로 변경해 보십시오.

while(($file = readdir($handle)) !== FALSE)
{
    $results_array[] = $file;
}
closedir($handle);

glob() 및 예:

/* 
 * glob() examples
 */

// get the array of full paths
$result = glob( 'path/*' );

// get the array of file names
$result = array_map( function( $item ) {
    return basename( $item );
}, glob( 'path/*' ) );


/* 
 * FilesystemIterator examples
 */

// get the array of file names by using FilesystemIterator and array_map()
$result = array_map( function( $item ) {
    // $item: SplFileInfo object
    return $item->getFilename();
}, iterator_to_array( new FilesystemIterator( 'path' ), false ) );

// get the array of file names by using FilesystemIterator and iterator_apply() filter
$it = new FilesystemIterator( 'path' );
iterator_apply( 
    $it, 
    function( $item, &$result ) {
        // $item: FilesystemIterator object that points to current element
        $result[] = (string) $item;
        // The function must return TRUE in order to continue iterating
        return true;
    }, 
    array( $it, &$result )
);

그냥 한번 해보는 게 어때?scandir(Path)기능.빠르고 쉽게 구현할 수 있습니다.

구문:

$files = scandir("somePath");

이 함수는 파일 목록을 배열로 반환합니다.

결과를 보려면

var_dump($files);

또는

foreach($files as $file)
{ 
echo $file."< br>";
} 

디렉토리 및 파일을 나열하는 또 다른 방법은RecursiveTreeIterator답변은 다음과 같습니다.https://stackoverflow.com/a/37548504/2032235

에 대한 자세한 설명RecursiveIteratorIterator및 PHP의 반복기는 https://stackoverflow.com/a/12236744/2032235 에서 찾을 수 있습니다.

다음 코드를 사용합니다.

<?php
    $directory = "Images";
    echo "<div id='images'><p>$directory ...<p>";
    $Files = glob("Images/S*.jpg");
    foreach ($Files as $file) {
        echo "$file<br>";
    }
    echo "</div>";
?>

용도:

if ($handle = opendir("C:\wamp\www\yoursite/download/")) {

    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<b>" . preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry) . "</b>";
        }
    }
    closedir($handle);
}

출처 : http://chandreshrana.blogspot.com/2016/08/how-to-fetch-all-files-name-from-folder.html

디렉터리에 포함된 모든 파일을 탐색하는 재귀 코드('$path'에는 디렉터리의 경로가 포함됩니다):

function explore_directory($path)
{
    $scans = scandir($path);

    foreach($scans as $scan)
    {
        $new_path = $path.$scan;

        if(is_dir($new_path))
        {
            $new_path = $new_path."/";
            explore_directory($new_path);
        }
        else // A file
        {
            /*
                  Body of code
            */
        }
    }
}

내가 이걸 위해 만든 작은 것:

function getFiles($path) {
    if (is_dir($path)) {
        $res = array();
        foreach (array_filter(glob($path ."*"), 'is_file') as $file) {
            array_push($res, str_replace($path, "", $file));                
        }
        return $res;
    }
    return false;
}

언급URL : https://stackoverflow.com/questions/2922954/getting-the-names-of-all-files-in-a-directory-with-php

반응형