Skip to content
Related Articles

Related Articles

PHP | scandir( ) Function
  • Last Updated : 03 Jul, 2018

The scandir() function in PHP is an inbuilt function which 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 Used:
The scandir() function in PHP accepts three parameters.

  • directory : It is a mandatory parameter which specifies the path.
  • sorting_order: It is an optional parameter which specifies the sorting order. Alphabetically ascending order (0) is the default sort order. It can be set to SCANDIR_SORT_DESCENDING or 1 to sort in alphabetically descending order, or SCANDIR_SORT_NONE to return the result unsorted.
  • context : It is an optional parameter which specifies the behaviorn of the stream.

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



Errors And Exceptions

  1. The scandir() function throws an error of level E_WARNING if the directory specified is not a directory.
  2. Doing a recursive scandir will on a directory which has many files will likely either slow down your application or cause a high rise in RAM consumption due to the large size of the generated array.

Below programs illustrate the scandir() function:

Program 1




<?php
// specifying directory
$mydir = '/docs';
  
//scanning files in a given diretory 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
)

Program 2




<?php
// specifying directory
$mydir = '/docs';
  
//scanning files in a given diretory 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] => .
)

Program 3




<?php
// specifying directory
$mydir = '/docs';
  
//scanning files in a given diretory in unsorted order
$myfiles = scandir($mydir, SCANDIR_SORT_NONE);
  
//displaying the files in the directory
print_r($myfiles);
?></div>

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :