Open In App

PHP scandir( ) Function

In this article, we will see how to get all the files from the current or specified directory using the scandir() function in PHP. The scandir() function in PHP is an inbuilt function that is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path. The directory, stream behavior, and sorting_order of the files and directories are passed as a parameter to the scandir() function and it returns an array of filenames on success, or false on failure. 

Syntax:

scandir(directory, sorting_order, context);

Parameters: The scandir() function in PHP accepts 3 parameters that are listed below:

Return Value: It returns an array of filenames on success, or false on failure.

Errors And Exceptions:

Approach: In order to get all the files from the particular directory, we need to specify the complete path of the file & store the path value in the variable as $mydir. Then use the scandir() function that will scan for the files in a current or specific directory & return an array of files and directories. By default, it will be aligned in the alphabetically ascending order & 0 as default sort order, 1 for sorting in alphabetically descending order & the SCANDIR_SORT_NONE  for unsorted order.

Example 1: The below example illustrate the scandir() function that will scan the files & return value will be in the ascending order.




<?php
   
  // Specifying directory
  $mydir = '/docs';
 
  // Scanning files in a given directory in ascending order
  $myfiles = scandir($mydir);
 
  // Displaying the files in the directory
  print_r($myfiles);
?>

Output:

(
[0] => .
[1] => ..
[2] => aboutus.php
[3] => contact.php
[4] => index.php 
[5] => terms.php
)

Example 2: This example illustrates the scandir() function that will scan the files & return value will be in the descending order.




<?php
   
  // Specifying directory
  $mydir = '/docs';
 
  // Scanning files in a given directory in descending order
  $myfiles = scandir($mydir, 1);
 
  // Displaying the files in the directory
  print_r($myfiles);
?>

Output:

 Array
(
[0] => terms.php
[1] => index.php 
[2] => contact.php
[3] => aboutus.php
[4] => ..
[5] => .
)

Example 3: This example illustrates the scandir() function that will scan the files & return value will be in the unsorted order.




<?php
  // Specifying directory
  $mydir = '/docs';
 
  // Scanning files in a given directory in unsorted order
  $myfiles = scandir($mydir, SCANDIR_SORT_NONE);
 
  // Displaying the files in the directory
  print_r($myfiles);
?>

Output:

 Array
(
[0] => .
[1] => ..
[2] => contact.php
[3] => terms.php
[4] => index.php 
[5] => aboutus.php
)

Reference: http://php.net/manual/en/function.scandir.php


Article Tags :