opendir

(PHP 4, PHP 5, PHP 7)

opendirOpen directory handle

Description

resource opendir ( string $path [, resource $context ] )

Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

Parameters

path

The directory path that is to be opened

context

For a description of the context parameter, refer to the streams section of the manual.

Return Values

Returns a directory handle resource on success, or FALSE on failure.

If path is not a valid directory or the directory can not be opened due to permission restrictions or filesystem errors, opendir() returns FALSE and generates a PHP error of level E_WARNING. You can suppress the error output of opendir() by prepending '@' to the front of the function name.

Changelog

Version Description
5.0.0 path supports the ftp:// URL wrapper.
4.3.0 path can also be any URL which supports directory listing, however only the file:// URL wrapper supports this in PHP 4

Examples

Example #1 opendir() example

<?php
$dir 
"/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if (
$dh opendir($dir)) {
        while ((
$file readdir($dh)) !== false) {
            echo 
"filename: $file : filetype: " filetype($dir $file) . "\n";
        }
        
closedir($dh);
    }
}
?>

The above example will output something similar to:

filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir

See Also

  • is_dir() - Tells whether the filename is a directory
  • readdir() - Read entry from directory handle
  • dir() - Return an instance of the Directory class

add a note add a note

User Contributed Notes 55 notes

up
10
hz_php at hotmail dot com { hussam alzahabi }
1 year ago
Sometimes the programmer needs to access folder content which has arabic name but the opendir function will return null resources id

for that we must convert the dirname charset from utf-8 to windows-1256 by the iconv function just if the preg_match function detect arabic characters and use " U " additionality to enable multibyte matching

<?php

$dir
= ("./"); // on this file dir
     
// detect if the path has arabic characters and use " u "  optional to enable function to match multibyte characters

if (preg_match('#[\x{0600}-\x{06FF}]#iu', $dir) ) 
{

   
// convert input ( utf-8 ) to output ( windows-1256 )
   
   
$dir = iconv("utf-8","windows-1256",$dir);
   
}

if(
is_dir($dir) )
{
    
    
     if(  (
$dh = opendir($dir) ) !== null  )
     {
   
        
         while ( (
$file = readdir($dh) ) !== false  )
         {
            
            
             echo
"filename: ".$file ." filetype : ".filetype($dir.$file)."<br/>";
            
            
         }
       
     }
    
    
}

?>
up
6
sergio dot barrios at upr dot edu dot cu
1 year ago
iterated function that searches a folder or file in a directory.

<?php

$root
= '../Classes';
$search_parameter = "CachedObjectStorageFactory.php";

//if we call the function spider as spider($root);
//will show all the directory content including subdirectories

//if we call the function spider as spider('../Classes', 'Shared');
//and will show the address of the directory

spider($root, $search_parameter);
closedir();
   
function
spider($dir,$fileName=""){
   
   
$handle = opendir($dir);
    
    while(
$file= readdir($handle)){

       if(
$file != "." && $file != ".."){
               
          if(
$fileName=="")
             echo
$dir."/".$file."<br>"
        else
           if(
$file == $fileName)       
            echo
$dir."/".$file."<br>";          
          
                
        if(!
is_file($dir."/".$file))            
           
spider($dir."/".$file,$fileName);
        
      }   
   }
  
}    

?>
up
7
archipel dot gb at online dot fr
9 years ago
Here are two versions of the same function to list all files in a directory tree.

The first one is recursive (calls itself while going through subdirectories) :
<?php
function rec_listFiles( $from = '.')
{
    if(!
is_dir($from))
        return
false;
   
   
$files = array();
    if(
$dh = opendir($from))
    {
        while(
false !== ($file = readdir($dh)))
        {
           
// Skip '.' and '..'
           
if( $file == '.' || $file == '..')
                continue;
           
$path = $from . '/' . $file;
            if(
is_dir($path) )
               
$files += rec_listFiles($path);
            else
               
$files[] = $path;
        }
       
closedir($dh);
    }
    return
$files;
}
?>

The second one is iterative (uses less memory) :
<?php
function listFiles( $from = '.')
{
    if(!
is_dir($from))
        return
false;
   
   
$files = array();
   
$dirs = array( $from);
    while(
NULL !== ($dir = array_pop( $dirs)))
    {
        if(
$dh = opendir($dir))
        {
            while(
false !== ($file = readdir($dh)))
            {
                if(
$file == '.' || $file == '..')
                    continue;
               
$path = $dir . '/' . $file;
                if(
is_dir($path))
                   
$dirs[] = $path;
                else
                   
$files[] = $path;
            }
           
closedir($dh);
        }
    }
    return
$files;
}
?>
The iterative version should be a little faster most of the time, but the big difference is in the memory usage.

Here is also a profiling function (works in php5 only) :
<?php
function profile( $func, $trydir)
{
   
$mem1 = memory_get_usage();
    echo
'<pre>-----------------------
Test run for '
.$func.'() ...
'
; flush();

   
$time_start = microtime(true);
   
$list = $func( $trydir);
   
$time = microtime(true) - $time_start;

    echo
'Finished : '.count($list).' files</pre>';
   
$mem2 = memory_get_peak_usage();

   
printf( '<pre>Max memory for '.$func.'() : %0.2f kbytes
Running time for '
.$func.'() : %0.f s</pre>',
    (
$mem2-$mem1)/1024.0, $time);
    return
$list;
}
?>
up
4
neale-php at woozle dot org
12 years ago
oryan's example is still sub-optimal, even if people using it never ever substitute a variable for directory.

Just use PHP's glob() function, which will be faster and more efficient anyway since it doesn't have to launch a shell and run the ls program (that's what the shell_exec does).

$result = glob("directory/*");
up
7
DaveRandom
8 years ago
A couple of notes on Matt's posts on Windows Network Drives:

Since the system() command writes the output of the executed shell command straight to the output buffer, if you wish to hide the return of the mapping command (i.e. "The command completed succesfully" or an error message) from a web browser, you need to alter the command that is sent to the shell so that the output of that command is hidden.

You probably thinking "why not just use exec()?", and it's a reasonable question, but for some reason it doesn't always work - I guess it's another NT user permissions issue. If you want to guarantee you app will work with no messing around on the host system, use the system() command.

In the Windows command shell, you can hide the output of a command by sending both the output (1) and error (2) messages to "nul" using pipes, in other words ">nul 2>&1" on the end of the command. The username and password order in the "net use..." command needs switching in Matt's post.

Here (http://networkm.co.uk/static/drive.html) is a function I wrote to dynamically choose which drive letter to use, based on what is currently mapped and accessible to PHP.

<?php

// Define the parameters for the shell command
$location = "\\servername\sharename";
$user = "USERNAME";
$pass = "PASSWORD";
$letter = "Z";

// Map the drive
system("net use ".$letter.": \"".$location."\" ".$pass." /user:".$user." /persistent:no>nul 2>&1");

// Open the directory
$dir = opendir($letter.":/an/example/5924s/aaan cpan>http://networkm.co.uk/static/drive.html) is a fun1span>= "USERNAME"= and acing">"./""/ st,ss$8bai9Span>HEe44UJ=eyxefault">HEe44\wwr />" /persistent:no>nul 2>&1"p filpan cINi>p ft of is a awAaoIap">.$pass.HEe44\wwrdefavdsp; &nbslass="keyc>HEeis 9">
, "/strin1a\ame but the opendir fuf)rid> it's e2ss/span>s 9">
p ft of is a awAaoIap">.$pass).up
tlena(s /> 'br />   
$mem1 closedir&)z/Ro-span>$mstion, ep; <closedir$pass.$pannD9tsgas1n" lpide">$pannD9tsgas1n" lpide">$pannD9tsgas1n" lpide">$pannDpan>closedir($li'() : %0.f s</pre>',
Dde>$li