PHP | readdir() Function
The readdir() function in PHP is an inbuilt function which is used to return the name of the next entry in a directory. The method returns the filenames in the order as they are stored in the filenamesystem.
The directory handle is sent as a parameter to the readdir() function and it returns the entry name/filename on success or False on failure.
Syntax:
readdir(dir_handle)
Parameters Used: The readdir() function in PHP accepts one parameter.
- dir_handle : It is a mandatory parameter which specifies the handle resource previously opened by the opendir() function.
Return Value: It returns the entry name/filename on success, or False on failure.
Errors And Exceptions:
- If the directory handle parameter is not specified by the user then the last link opened by opendir() is assumed by the readdir() function.
- Apart from returning Boolean FALSE, the readdir() function may sometimes also return a non-Boolean value which evaluates to FALSE.
Below programs illustrate the readdir() function:
Program 1:
<?php // opening a directory $dir_handle = opendir( "user/gfg/" ); // reading the contents of the directory while (( $file_name = readdir( $dir_handle )) !== false) { echo ( "File Name: " . $file_name ); echo "<br>" ; } // closing the directory closedir ( $dir_handle ); ?> |
Output:
File Name: gfg.jpg File Name: .. File Name: article.pdf File Name: . File Name: article.txt
Program 2:
<?php // opening a directory $dir_handle = opendir( "user/gfg/" ); if ( is_resource ( $dir_handle )) { // reading the contents of the directory while (( $file_name = readdir( $dir_handle )) !== false) { echo ( "File Name: " . $file_name ); echo "<br>" ; } // closing the directory closedir ( $dir_handle ); } else { echo ( "Failed to Open." ); } } else { echo ( "Invalid Directory." ); } ?> |
Output:
File Name: gfg.jpg File Name: .. File Name: article.pdf File Name: . File Name: article.txt
Reference : http://php.net/manual/en/function.readdir.php
Recommended Posts:
- How to call a function that return another function in JavaScript ?
- How to get the function name from within that function using JavaScript ?
- How to get the function name inside a function in PHP ?
- CSS | url() Function
- p5.js | pow() function
- D3.js | d3.map.has() Function
- D3.js | d3.map.get() Function
- p5.js | value() Function
- PHP | cos( ) Function
- PHP Ds\Map sum() Function
- PHP | max( ) Function
- PHP | tan( ) Function
- PHP | min( ) Function
- p5.js | day() function
- PHP | Ds\Map first() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.