Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Directory Functions

Directory Functions

Introduction

Requirements

No external libraries are needed to build this extension.

Installation

There is no installation needed to use these functions; they are part of the PHP core.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

DIRECTORY_SEPARATOR (string)
PATH_SEPARATOR (string)
Note:

The PATH_SEPARATOR was introduced with PHP 4.3.0-RC2.

See Also

For related functions such as dirname(), is_dir(), mkdir(), and rmdir(), see the Filesystem section.

Table of Contents

chdir — Change directory
chroot — Change the root directory
dir — Return an instance of the Directory class
closedir — Close directory handle
getcwd — Gets the current working directory
opendir — Open directory handle
readdir — Read entry from directory handle
rewinddir — Rewind directory handle
scandir — List files and directories inside the specified path

Code Examples / Notes » ref.dir

engin bzzzt biz

To join directory and file names in a cross-platform manner you can use the following function.
function join_path()
{
$num_args = func_num_args();
$args = func_get_args();
$path = $args[0];

if( $num_args > 1 )
{
for ($i = 1; $i < $num_args; $i++)
{
$path .= DIRECTORY_SEPARATOR.$args[$i];
}
}

return $path;
}
It should do the following:
$src = join_path( '/foo', 'bar', 'john.jpg' );
echo $src; // On *nix -> /foo/bar/john.jpg
$src = join_path( 'C:\www', 'domain.com', 'foo.jpg' );
echo $src; // On win32 -> C:\\www\\domain.com\\foo.jpg


adrian

Samba mounts under a Windows environment are not accessible using the mounted drive letter. For instance, if you have drive X: in Windows mounted to //example.local/shared_dir (where example.local is a *nix box running Samba), the following constructs
$dir = "X:\\data\\";
$handle = opendir( $dir );
or
$d = dir( $dir );
will return a warning message "failed to open dir: No error"
On the other hand, using the underlying mapping info works just fine. For example:
$dir = "//example.local/shared_dir/data";
$handle = opendir( $dir );
or
$d = dir( $dir );
Both cases do what they're expected to.


jean-paul wattiaux

Mine works as long as the samba volume is actually mounted. Having it listed in the "My Computer" window doesn't warrant that.

dkflbk

I wrote a simple backup script which puts all files in his folder (and all of the sub-folders) in one TAR archive...
(It's classic TAR format not USTAR, so filename and path to it can't be longer then 99 chars)
<?php
/***********************************************************
*   Title:  Classic-TAR based backup script v0.0.1-dev
 **********************************************************/
Class Tar_by_Vladson {
var $tar_file;
var $fp;
function Tar_by_Vladson($tar_file='backup.tar') {
$this->tar_file = $tar_file;
$this->fp = fopen($this->tar_file, "wb");
$tree = $this->build_tree();
$this->process_tree($tree);
fputs($this->fp, pack("a512", ""));
fclose($this->fp);
}
function build_tree($dir='.'){
$handle = opendir($dir);
while(false !== ($readdir = readdir($handle))){
if($readdir != '.' && $readdir != '..'){
$path = $dir.'/'.$readdir;
if (is_file($path)) {
$output[] = substr($path, 2, strlen($path));
} elseif (is_dir($path)) {
$output[] = substr($path, 2, strlen($path)).'/';
$output = array_merge($output, $this->build_tree($path));
}
}
}
closedir($handle);
return $output;
}
function process_tree($tree) {
foreach( $tree as $pathfile ) {
if (substr($pathfile, -1, 1) == '/') {
fputs($this->fp, $this->build_header($pathfile));
} elseif ($pathfile != $this->tar_file) {
$filesize = filesize($pathfile);
$block_len = 512*ceil($filesize/512)-$filesize;
fputs($this->fp, $this->build_header($pathfile));
fputs($this->fp, file_get_contents($pathfile));
fputs($this->fp, pack("a".$block_len, ""));
}
}
return true;
}
function build_header($pathfile) {
if ( strlen($pathfile) > 99 ) die('Error');
$info = stat($pathfile);
if ( is_dir($pathfile) ) $info[7] = 0;
$header = pack("a100a8a8a8a12A12a8a1a100a255",
$pathfile,
sprintf("%6s ", decoct($info[2])),
sprintf("%6s ", decoct($info[4])),
sprintf("%6s ", decoct($info[5])),
sprintf("%11s ",decoct($info[7])),
sprintf("%11s", decoct($info[9])),
sprintf("%8s", " "),
(is_dir($pathfile) ? "5" : "0"),
"",
""
);
clearstatcache();
$checksum = 0;
for ($i=0; $i<512; $i++) {
$checksum += ord(substr($header,$i,1));
}
$checksum_data = pack(
"a8", sprintf("%6s ", decoct($checksum))
);
for ($i=0, $j=148; $i<7; $i++, $j++)
$header[$j] = $checksum_data[$i];
return $header;
}
}
header('Content-type: text/plain');
$start_time = array_sum(explode(chr(32), microtime()));
$tar = & new Tar_by_Vladson();
$finish_time = array_sum(explode(chr(32), microtime()));
printf("The time taken: %f seconds", ($finish_time - $start_time));
?>


msh

I would like to present these two simple functions for generating a complete directory listing - as I feel the other examples are to restrictive in terms of usage.
function dirTree($dir) {
$d = dir($dir);
while (false !== ($entry = $d->read())) {
if($entry != '.' && $entry != '..' && is_dir($dir.$entry))
$arDir[$entry] = dirTree($dir.$entry.'/');
}
$d->close();
return $arDir;
}
function printTree($array, $level=0) {
foreach($array as $key => $value) {
echo "<div class='dir' style='width: ".($level*20)."px;'>&nbsp;</div>".$key."<br/>\n";
if(is_array($value))
printTree($value, $level+1);
}
}
Usage is as simple as this:
$dir = "<any directory you like>";
$arDirTree = dirTree($dir);
printTree($arDirTree);
It is easy to add files to the tree also - so enjoy.


phdwight

I have posted this same observation in scandir, and found out that it is not limited to scandir alone but to ALL directory functions.
Directory functions DOES NOT currently supports Japanese characters.


nicolas merlet - admin

Here is a very similar function to *scandir*, if you are still using PHP4...
This recursive function will return an indexed array containing all directories or files or both (depending on parameters). You can specify the depth you want, as explained below.
<?php
// $path : path to browse
// $maxdepth : how deep to browse (-1=unlimited)
// $mode : "FULL"|"DIRS"|"FILES"
// $d : must not be defined
 
function searchdir ( $path , $maxdepth = -1 , $mode = "FULL" , $d = 0 )
{
  if ( substr ( $path , strlen ( $path ) - 1 ) != '/' ) { $path .= '/' ; }      
  $dirlist = array () ;
  if ( $mode != "FILES" ) { $dirlist[] = $path ; }
  if ( $handle = opendir ( $path ) )
  {
      while ( false !== ( $file = readdir ( $handle ) ) )
      {
          if ( $file != '.' && $file != '..' )
          {
              $file = $path . $file ;
              if ( ! is_dir ( $file ) ) { if ( $mode != "DIRS" ) { $dirlist[] = $file ; } }
              elseif ( $d >=0 && ($d < $maxdepth || $maxdepth < 0) )
              {
                  $result = searchdir ( $file . '/' , $maxdepth , $mode , $d + 1 ) ;
                  $dirlist = array_merge ( $dirlist , $result ) ;
              }
      }
      }
      closedir ( $handle ) ;
  }
  if ( $d == 0 ) { natcasesort ( $dirlist ) ; }
  return ( $dirlist ) ;
}
?>


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker