What is the function of the php scandir function?

The scandir() function is used in PHP to retrieve a list of files and subdirectories in a specified directory. It returns an array containing the contents of the directory, including the names of all files and subdirectories within it.

More specifically, the syntax of the scandir() function is as follows:

array scandir(string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]])
  1. The $directory parameter specifies the directory path to be scanned.
  2. The $sorting_order parameter is optional and is used to specify the order of sorting, which can be either SCANDIR_SORT_ASCENDING (default) or SCANDIR_SORT_DESCENDING.
  3. The $context parameter is optional and is used to specify the context (such as access permissions), typically when working with stream resources.

The following example demonstrates how to use the scandir() function to list files and subdirectories in a specified directory.

$dir = '/path/to/directory/';
$files = scandir($dir);

foreach($files as $file) {
    echo $file . "\n";
}

This will output the names of all files and subdirectories in the specified directory /path/to/directory/. The scandir() function is typically used for creating custom directory browsers, file managers, and other situations where listing directory contents is needed.

Leave a Reply 0

Your email address will not be published. Required fields are marked *