Skip to end of metadata
Go to start of metadata

scandir( $path) returns the searched result in array. If you want to implement recursive scan for sub directories, you can implement it by checking filetype().

$result = scandir(directory, order, context)

  • it returns false on failure.


<?php

$r = scandir("/etc/");
print_r( $r);

?>


Below is another example to find files in regexp.

// Programmed by Chun Kang - 2020-03-27
function findfiles( $path, $regexp="", $order=0)
{
    $r = scandir( $path, $order); // $order: 0->ascending / 1->descending
    if ($r==false) $ret=$r;
    else
    {
        $ret=array();
        $i=count($r)-1;
        for($i=0; $i<count($r); $i++)
        {
            if (
            		(($regexp=="") || preg_match('/' . $regexp . '/', $r[$i]))
            		&& strlen($r[$i])
            		&& $r[$i]!='.'
            		&& $r[$i]!='..'
            	) $ret[]=$r[$i];
        }
    }
    return $ret;
}

$r = findfiles( "/repostirory", "qsok(.*)mysql");
print_r($r);

Below is another example to find files including sub directories combined with regexp:

function findfiles( $path, $regexp=NULL, $order=0)
{
        $ret = array();

        $searchEntry = array();
        $searchEntry []= $path;

        $hasRegexp = strlen($regexp);

        $entry_cnt=0;
        while( $entry_cnt<count($searchEntry))
        {
                $entryPath = $searchEntry[$entry_cnt++];

                echo "scan - {$entryPath}\n";
                $r = scandir( $entryPath, $order); // $order: 0->ascending / 1->descending
                foreach($r as $filename)
                {
                        $full_path = $entryPath . "/" . $filename;
                        echo "[{$filename}] - {$full_path}\n";
                        if (($filename!=".") && ($filename!="..")) 
                        {
                                if ( filetype( $full_path) == "dir") $searchEntry []= $full_path;
                                else if (
                                                (!$hasRegexp || preg_match('/' . $regexp . '/', $filename))
                                                && strlen($filename)
                                        ) $ret[]=str_replace( $path . "/", "", $full_path);        
                        }
                }
        }

        return (count($ret) ? $ret: NULL);
}