PHP __DIR__ Demo

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 ();
?>

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.phpCode 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__ ?>

Code language: PHP (php)

The index.php includes both header.php and footer.php files. It also shows the value of the __DIR__ constant:

 require 'inc/header.php' ?> 

Home

echo __DIR__ ?>

require 'inc/footer.php' ?>
Code language: PHP (php)

The following shows the output on the web browser:

Home C:\xampp\htdocs\web C:\xampp\htdocs\web\incCode language: PHP (php)

The __DIR__ in the index.php returns the current directory of the index.php C:\xampp\htdocs\web while the __DIR__ in the footer.php file returns the directory of the footer.php file C:\xampp\htdocs\web\inc .

Why using PHP __DIR__

Suppose that you have a project with the following directory structure:

. ├── admin │ └── dashboard │ └── index.php ├── config │ └── app.php ├── inc │ ├── footer.php │ └── header.php └── public └── index.phpCode language: CSS (css)

The config/app.php contains the application’s configuration:

 define('APP_NAME', 'My Awesome App');Code language: PHP (php)

The header.php contains the header part of a page. It also includes the config/app.php file and uses the APP_NAME constant:

 require '../config/app.php' ?> "en"> "UTF-8"> "viewport" content="width=device-width, initial-scale=1.0">   Code language: PHP (php)

The footer.php contains the closing tags of the body and html elements:

The public/index.php file includes both header.php and footer.php files:

 require '../inc/header.php' ?> 

Home

require '../inc/footer.php'?>
Code language: PHP (php)

If you navigate to the http://localhost/web/public/index.php , you’ll see the following output when you view the source of the page:

 "en"> "UTF-8"> "viewport" content="width=device-width, initial-scale=1.0">   

Dashboard

Code language: PHP (php)

So the index.php page in the public directory works as expected.

The index.php in the admin/dashboard also includes the header.php and footer.php files:

 require '../../inc/header.php' ?> 

Dashboard

require '../../inc/footer.php' ?>
Code language: PHP (php)

When you browse the page http://localhost/web/admin/dashboard/index.php , you’ll see the following error:

Warning: require(../config/app.php): failed to open stream: No such file or directory in C:\xampp\htdocs\web\inc\header.php on line 1 Fatal error: require(): Failed opening required '../config/app.php' (include_path='\xampp\php\PEAR') in C:\xampp\htdocs\web\inc\header.php on line 1Code language: PHP (php)

The error message shows that the header.php cannot load the ‘../config/app.php’ file.

When the index.php in the admin/dashboard directory loads the code from the header.php , it’ll find the config/app.php inside the admin directory, not root directory.

Since the admin directory doesn’t have the config/app.php file, PHP issues an error.

To fix this issue, you can use the __DIR__ when you include the config.php in the header.php file like this:

 require __DIR__. '/../config/app.php' ?>Code language: PHP (php)

The index.php in the admin/dashboard will work correctly.

This is because when PHP loads the inc/header.php file from either public/index.php or admin/dashboard/index.php , the __DIR__ inside the inc/header.php always returns C:\xampp\htdocs\web\inc .

Therefore, it’s a good practice to use the __DIR__ constant when you include a file.

Summary

  • PHP __DIR__ returns the directory of a file or the directory of the include file when the file is used as an include.
  • Use __DIR__ when you include a file.

Источник

Читайте также:  Bujet ru article 288765 php
Оцените статью