PHP scandir function
The PHP scandir
function will return an indexed array of the files and directories within the specified directory path.
scandir(string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING, ?resource $context = null): array|falseSintaxis / Sintax
$folderContent= scandir($directory,(optional)$sorting__order,(optional)$context)
Parameters
$directory
– contains the path of the directory to be scanned.
$sorting_order
– this parameter indicates the order in which the array will be returned. It can have three possible values:
- Ascending order (default)
- Descending order (use the constant
SCANDIR_SORT_DESCENDING
) - No specific order (use the constant
SCANDIR_SORT_NONE
)
$context
– The value of the context parameter should be a context resource created with the stream_context_create()
function. This context resource contains options and parameters that define how the directory scanning will be performed. These options may include context configurations related to file permissions, error handling, file filters, among others.
In general, this parameter is not used unless there is a need to control the stream (a sequence of data transferred from a source to a destination continuously).
Returns
It returns an indexed array
of files and directories if successful.
It returns false
in case of failure. If the given directory is not a directory, it returns false
and generates an E_WARNING error.
Examples of PHPscandir function
The following example is the one mentioned on php.net:
simple scandisk sample$dir = '/tmp'; $files1 = scandir($dir); $files2 = scandir($dir, SCANDIR_SORT_DESCENDING); print_r($files1); print_r($files2);
Array ( [0] => . [1] => .. [2] => bar.php [3] => foo.txt [4] => somedir ) Array ( [0] => somedir [1] => foo.txt [2] => bar.php [3] => .. [4] => . )
The following examples have not been checked, but they comply with the $context
parameter, so I have left them as a guide.
HTTP context: The following example is a bit far-fetched, but it could happen.
HTTP context example$httpContext = stream_context_create([ 'http' => [ 'method' => 'GET', 'header' => 'Authorization: Bearer your_token', ], ]); $files = scandir($directory, 0, $httpContext);
File Context: This would actually be our default
file context$fileContext = stream_context_create([ 'file' => [ 'mode' => 'r', ], ]); $files = scandir($directory, 0, $fileContext);
SSL Context (for secure connections):
SSL context$sslContext = stream_context_create([ 'ssl' => [ 'verify_peer' => true, 'verify_peer_name' => true, ], ]); $files = scandir($directory, 0, $sslContext);