itsource

디렉토리의 모든 파일을 루프하는 PHP 스크립트?

mycopycode 2022. 9. 25. 00:22
반응형

디렉토리의 모든 파일을 루프하는 PHP 스크립트?

포맷, 인쇄, 링크 추가 등 파일 이름을 사용할 수 있도록 디렉토리 내의 모든 파일을 루프하는 PHP 스크립트를 찾고 있습니다.파일을 이름, 형식 또는 작성/추가/수정 날짜별로 정렬할 수 있도록 하고 싶습니다.(멋진 디렉토리 「인덱스」를 생각해 주세요).스크립트 자체나 다른 "시스템" 파일 등의 파일 목록에 제외 항목을 추가할 수도 있습니다.(예:.그리고..."디렉토리」)

스크립트를 수정할 수 있으면 좋기 때문에 PHP 문서를 보고 직접 작성하는 방법을 배우고 싶습니다.다만, 기존의 스크립트나 튜토리얼등이 있으면 가르쳐 주세요.

디렉토리를 사용할 수 있습니다.반복기php 매뉴얼의 예:

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        var_dump($fileinfo->getFilename());
    }
}
?>

디렉토리에 액세스 할 수 없는 경우반복기 클래스는 다음을 수행합니다.

<?php
$path = "/path/to/files";

if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ('.' === $file) continue;
        if ('..' === $file) continue;

        // do something with the file
    }
    closedir($handle);
}
?>

를 사용합니다.scandir()기능:

<?php
    $directory = '/path/to/files';

    if (!is_dir($directory)) {
        exit('Invalid diretory path');
    }

    $files = array();
    foreach (scandir($directory) as $file) {
        if ($file !== '.' && $file !== '..') {
            $files[] = $file;
        }
    }

    var_dump($files);
?>

또, 다음과 같은 기능을 사용할 수 있습니다.FilesystemIterator그럼 더 적은 코드가 필요하게 됩니다.DirectoryIterator, 및 자동으로 삭제합니다..그리고....

// Let's traverse the images directory
$fileSystemIterator = new FilesystemIterator('images');

$entries = array();
foreach ($fileSystemIterator as $fileInfo){
    $entries[] = $fileInfo->getFilename();
}

var_dump($entries);

//OUTPUT
object(FilesystemIterator)[1]

array (size=14)
  0 => string 'aa[1].jpg' (length=9)
  1 => string 'Chrysanthemum.jpg' (length=17)
  2 => string 'Desert.jpg' (length=10)
  3 => string 'giphy_billclinton_sad.gif' (length=25)
  4 => string 'giphy_shut_your.gif' (length=19)
  5 => string 'Hydrangeas.jpg' (length=14)
  6 => string 'Jellyfish.jpg' (length=13)
  7 => string 'Koala.jpg' (length=9)
  8 => string 'Lighthouse.jpg' (length=14)
  9 => string 'Penguins.jpg' (length=12)
  10 => string 'pnggrad16rgb.png' (length=16)
  11 => string 'pnggrad16rgba.png' (length=17)
  12 => string 'pnggradHDrgba.png' (length=17)
  13 => string 'Tulips.jpg' (length=10)

링크: http://php.net/manual/en/class.filesystemiterator.php

이 코드를 사용하면, 디렉토리를 재귀적으로 루프 할 수 있습니다.

$path = "/home/myhome";
$rdi = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME);
foreach (new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::SELF_FIRST) as $file => $info) {
    echo $file."\n";
}

glob()에는 정렬 및 패턴 매칭을 위한 프로비저닝이 있습니다.반환값은 배열이므로 필요한 대부분의 작업을 수행할 수 있습니다.

대부분의 경우엔 네가 건너뛰고 싶어한다고 생각해.그리고...재귀가 있는 경우는 다음과 같습니다.

<?php

$rdi = new RecursiveDirectoryIterator('.', FilesystemIterator::SKIP_DOTS);
$rii = new RecursiveIteratorIterator($rdi);

foreach ($rii as $di) {
   echo $di->getFilename(), "\n";
}

https://php.net/class.recursivedirectoryiterator

완전성을 위해(이것은 트래픽이 많은 페이지인 것 같기 때문에) 이전 기능을 잊지 않도록 합시다.

$entries = [];
$d = dir("/"); // dir to scan
while (false !== ($entry = $d->read())) { // mind the strict bool check!
    if ($entry[0] == '.') continue; // ignore anything starting with a dot
    $entries[] = $entry;
}
$d->close();
sort($entries); // or whatever desired

print_r($entries);

이것도 할 수 있어요

$path = "/public";

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

foreach ($objects as $name => $object) {
  if ('.' === $object) continue;
  if ('..' === $object) continue;

str_replace('/public/', '/', $object->getPathname());

// for example : /public/admin/image.png => /admin/image.png

언급URL : https://stackoverflow.com/questions/4202175/php-script-to-loop-through-all-of-the-files-in-a-directory

반응형