Php this file directory
dir — Return an instance of the Directory class
Description
A pseudo-object-oriented mechanism for reading a directory. The given directory is opened.
Parameters
Return Values
Returns an instance of Directory , or false in case of error.
Changelog
Examples
Example #1 dir() example
Please note the fashion in which Directory::read() ‘s return value is checked in the example below. We are explicitly testing whether the return value is identical to (equal to and of the same type as — see Comparison Operators for more information) false since otherwise, any directory entry whose name evaluates to false will stop the loop.
$d = dir ( «/etc/php5» );
echo «Handle: » . $d -> handle . «\n» ;
echo «Path: » . $d -> path . «\n» ;
while ( false !== ( $entry = $d -> read ())) echo $entry . «\n» ;
>
$d -> close ();
?>?php
The above example will output something similar to:
Handle: Resource id #2 Path: /etc/php5 . .. apache cgi cli
Notes
Note:
The order in which directory entries are returned by the read method is system-dependent.
User Contributed Notes 20 notes
// simple juste use FilesystemIterator
// and you can skip dot and duble dot
// and use it in array
// new FilesystemIterator( PATH , OPTIONS ) : array
$array_file_list = new FilesystemIterator ( PATH_ROOT . ‘folder/’ , FilesystemIterator :: SKIP_DOTS );
This one’s pretty nice. After getting frustrated for hunting down .jpg files in my massive music collection (PHP would run out of memory), I thought there should be a preg_ls function.
function preg_ls ($path=».», $rec=false, $pat=»/.*/») // it’s going to be used repeatedly, ensure we compile it for speed.
$pat=preg_replace(«|(/.*/[^S]*)|s», «\\1S», $pat);
//Remove trailing slashes from path
while (substr($path,-1,1)==»/») $path=substr($path,0,-1);
//also, make sure that $path is a directory and repair any screwups
if (!is_dir($path)) $path=dirname($path);
//assert either truth or falsehoold of $rec, allow no scalars to mean truth
if ($rec!==true) $rec=false;
//get a directory handle
$d=dir($path);
//initialise the output array
$ret=Array();
//loop, reading until there’s no more to read
while (false!==($e=$d->read())) //Ignore parent- and self-links
if (($e==».»)||($e==»..»)) continue;
//If we’re working recursively and it’s a directory, grab and merge
if ($rec && is_dir($path.»/».$e)) $ret=array_merge($ret,preg_ls($path.»/».$e,$rec,$pat));
continue;
>
//If it don’t match, exclude it
if (!preg_match($pat,$e)) continue;
//In all other cases, add it to the output array
$ret[]=$path.»/».$e;
>
//finally, return the array
return $ret;
>
Not bad for a mere 18 lines, don’t you think?
foreach (preg_ls(«/etc/X11», true, «/.*\.conf/i») as $file) echo $file.»\n»;
Here my solution how to do effective recursiv directory listing.
/**
* example of use:
*/
$d = new RecDir ( «/etc/» , false );
echo «Path: » . $d -> getRootPath () . «\n» ;
while ( false !== ( $entry = $d -> read ())) echo $entry . «\n» ;
>
$d -> close ();
class RecDir
protected $currentPath ;
protected $slash ;
protected $rootPath ;
protected $recursiveTree ;
function __construct ( $rootPath , $win = false )
switch( $win )
case true :
$this -> slash = ‘\\’ ;
break;
default:
$this -> slash = ‘/’ ;
>
$this -> rootPath = $rootPath ;
$this -> currentPath = $rootPath ;
$this -> recursiveTree = array( dir ( $this -> rootPath ));
$this -> rewind ();
>
function __destruct ()
$this -> close ();
>
public function close ()
while( true === ( $d = array_pop ( $this -> recursiveTree )))
$d -> close ();
>
>
public function getRootPath ()
if(isset( $this -> rootPath ))
return $this -> rootPath ;
>
return false ;
>
public function getCurrentPath ()
if(isset( $this -> currentPath ))
return $this -> currentPath ;
>
return false ;
>
public function read ()
while( count ( $this -> recursiveTree )> 0 )
$d = end ( $this -> recursiveTree );
if(( false !== ( $entry = $d -> read ())))
if( $entry != ‘.’ && $entry != ‘..’ )
$path = $d -> path . $entry ;
if( is_file ( $path ))
return $path ;
>
elseif( is_dir ( $path . $this -> slash ))
$this -> currentPath = $path . $this -> slash ;
if( $child = @ dir ( $path . $this -> slash ))
$this -> recursiveTree [] = $child ;
>
>
>
>
else
array_pop ( $this -> recursiveTree )-> close ();
>
>
return false ;
>
public function rewind ()
$this -> closeChildren ();
$this -> rewindCurrent ();
>
public function rewindCurrent ()
return end ( $this -> recursiveTree )-> rewind ();
>
>
?>
Regarding samuel’s comment about the dir() function not supporting Unicode properly, it’s all in the encoding. The function does NOT internally change Unicode characters into question marks (?), as I was first led to believe. If you simply try to output them in UTF-8, they’ll show up just right.
Note that the dir object will use the default encoding for non-unicode programs on Windows with PHP 5.x.
So, if you have a file named with characters unsupported by the current default encoding, the dir->read() method will return a wrong entry.
/*
** This script is on the same directory than a file named with
** unsupported characters for the current default encoding.
*/
$d = dir ( «./» );
while( false !== ( $e = $d -> read ()))
echo $e . ‘
‘ ;
?>
This will print a «?» for every unsupported characters, and not the right file name. So take care if you check with is_file/is_dir right after enumerating.
PHP __DIR__
Summary: in this tutorial, you’ll learn about how to use the PHP __DIR__ magic constant when including a PHP file.
Introduction to the PHP __DIR__ magic constant
PHP 5.3 introduced a new magic constant called __DIR__ . When you reference the __DIR__ inside a file, it returns the directory of the file. The __DIR__ doesn’t include a trailing slash e.g., / or \ except it’s a root directory.
When you use the __DIR__ inside an include, the __DIR__ returns the directory of the included file.
Technically speaking, the __DIR__ is equivalent to the dirname(__FILE__) . However, using the __DIR__ is more concise than the dirname(__FILE__) .
Simple PHP __DIR__example
Suppose you have the following directory structure:
. ├── inc │ ├── footer.php │ └── header.php └── index.php
Code language: CSS (css)
The header.php contains the code of the header part:
"en"> "UTF-8"> "viewport" content="width=device-width, initial-scale=1.0"> Code language: PHP (php)
The footer.php contains the code of the footer part. It also shows the value of the __DIR__ constant:
echo __DIR__ ?>