SSISO Community

시소당

opendir

opendir
(PHP  3,  PHP  4  ,  PHP  5)

opendir  --  디렉토리  핸들을  엽니다.
설명
resource  opendir  (  string  path)


closedir(),  readdir(),  rewinddir()  호출에서  사용하는  디렉토리  핸들을  반환합니다.  

path가  유효하지  않은  디렉토리이거나,  권한  제한이나  파일시스템  에러로  인해  디렉토리를  열  수  없는  경우,  opendir()은  FALSE를  반환하고  E_WARNING  레벨의  PHP  에러를  발생합니다.  opendir()  앞에  '@'를  붙여  에러  출력을  없앨  수  있습니다.  

예  1.  opendir()  예제

<?php
$dir  =  "/tmp/";

//  알고  있는  디렉토리를  열어서,  내용을  읽어들이는  작업입니다.
if  (is_dir($dir))  {
      if  ($dh  =  opendir($dir))  {
              while  (($file  =  readdir($dh))  !==  false)  {
                      echo  "filename:  $file  :  filetype:  "  .  filetype($dir  .  $file)  .  "\n";
              }
              closedir($dh);
      }
}
?>    
  


PHP  4.3.0부터  path는  디렉토리  목록을  지원하는  URL일  수  있지만,  PHP  4.3에서는  file://  URL  래퍼만  지원합니다.  PHP  5.0.0부터는  ftp://  URL  래퍼도  지원합니다.  

참고:  is_dir(),  readdir(),  Dir  




  add  a  note  User  Contributed  Notes
opendir  
Lasse  Dalegaard
22-May-2005  04:25  
I  made  a  function  for  finding  all  files  in  a  specified  directory  and  all  subdirectories.  It  can  be  quite  usefull  when  searching  in  alot  of  files  in  alot  subdirectories.  The  function  returns  an  array  with  the  path  of  all  the  files  found.

<?
function  getFiles($directory)  {
      //  Try  to  open  the  directory
      if($dir  =  opendir($directory))  {
              //  Create  an  array  for  all  files  found
              $tmp  =  Array();

              //  Add  the  files
              while($file  =  readdir($dir))  {
                      //  Make  sure  the  file  exists
                      if($file  !=  "."  &&  $file  !=  ".."  &&  $file[0]  !=  '.')  {
                              //  If  it's  a  directiry,  list  all  files  within  it
                              if(is_dir($directory  .  "/"  .  $file))  {
                                      $tmp2  =  getFiles($directory  .  "/"  .  $file);
                                      if(is_array($tmp2))  {
                                              $tmp  =  array_merge($tmp,  $tmp2);
                                      }
                              }  else  {
                                      array_push($tmp,  $directory  .  "/"  .  $file);
                              }
                      }
              }

              //  Finish  off  the  function
              closedir($dir);
              return  $tmp;
      }
}

//  Example  of  use
print_r(getFiles('.'));  //  This  will  find  all  files  in  the  current  directory  and  all  subdirectories
?>  
brett  at  medeaproject  dot  co  dot  za
11-May-2005  04:02  
This  is  a  little  script  i  wrote  to  generate  a  home  page  on  my  dev  box  by  parsing  the  contents  of  my  htdocs  directory.  It  is  encapsulated  in  a  html  table

Arb  but  useful  if  you  are  as  lazy  as  I  am  ;)
<?
$handle  =  opendir("./");

while  (($file  =  readdir($handle))!==false)  {
    if(is_dir($file)){
      if($file  !=  "."  &&  $file  !=  ".."){?>
    <tr>
    <td  align="center"  bgcolor="FFFFFF"><a  href="<?=  $file;?>"><?php  echo  ucwords($file)?></a></strong></td>
    </tr>
    <?php

          }
    }
}
closedir($handle);
$handle  =  opendir("./");
while  (($file  =  readdir($handle))!==false)  {
    if(is_file($file)){
      if($file  !=  "."  &&  $file  !=  ".."){?>
    <tr>
    <td  align="center"  bgcolor="FFFFFF"><a  href="<?=  $file?>"><?php  echo  ucwords($file)?></a></strong></td>
    </tr>
    <?php

          }
    }
}
closedir($handle);
?>  
brett  at  medeaproject  dot  co  dot  za
11-May-2005  04:01  
This  is  a  little  script  i  wrote  to  generate  a  home  page  on  my  dev  box  by  parsing  the  contents  of  my  htdocs  directory.  It  is  encapsulated  in  a  html  table

Arb  but  useful  if  you  are  as  lazy  as  I  am  ;)
<?
$handle  =  opendir("./");

while  (($file  =  readdir($handle))!==false)  {
    if(is_dir($file)){
      if($file  !=  "."  &&  $file  !=  ".."){?>
    <tr>
    <td  align="center"  bgcolor="FFFFFF"><a  href="<?=  $file;?>"><?php  echo  ucwords($file)?></a></strong></td>
    </tr>
    <?php

          }
    }
}
closedir($handle);
$handle  =  opendir("./");
while  (($file  =  readdir($handle))!==false)  {
    if(is_file($file)){
      if($file  !=  "."  &&  $file  !=  ".."){?>
    <tr>
    <td  align="center"  bgcolor="FFFFFF"><a  href="<?=  $file?>"><?php  echo  ucwords($file)?></a></strong></td>
    </tr>
    <?php

          }
    }
}
closedir($handle);
?>  
iamnotanerd
30-Mar-2005  02:38  
Here  is  a  snippet  of  the  code  that  I  created  to  search  for  a  file..recursively  open  the  directories  and  search  for  a  match..
<?
function  search($target,  $directory){
          
      if(is_dir($directory)){
              $direc  =  opendir($directory);
              while(false  !==  ($file  =  readdir($direc))){
                      
                      if($file  !="."  &&  $file  !=  ".."){

                              if(is_file($directory."/".$file)){
                                      if(preg_match("/$target/i",  $file)){
                                                                                      echo  "<a  href=\"$directory/$file\">$file</a><br>";
                                                                              }
                              }else  if(is_dir($directory."/".$file)){
                                      search($target,$directory."/".$file);
                                      
                              }

                      }
              }
              closedir($direc);
      }

      return  ;
}
?>  
hendrik  dot  wermer  at  gmx  dot  de
08-Feb-2005  10:06  
Here's  another  version  of  directory  listing,  since  I  had  some  problems  using  the  examples  below.  It  will  display  the  content  of  the  current  directory,  sorted  by  directories  and  files.
You  can  also  search  subdirectories  by  setting  $maxDepth  >  0.  There's  a  link  to  other  directories,  so  you  can  easily  switch  to  the  parent  directory  or  to  other  directories  in  the  current  directory.
Hope  it  helps!

<?php
//  show  directory  content
function  showDir($dir,  $i,  $maxDepth){
      $i++;
      if($checkDir  =  opendir($dir)){
              $cDir  =  0;
              $cFile  =  0;
              //  check  all  files  in  $dir,  add  to  array  listDir  or  listFile
              while($file  =  readdir($checkDir)){
                      if($file  !=  "."  &&  $file  !=  ".."){
                              if(is_dir($dir  .  "/"  .  $file)){
                                      $listDir[$cDir]  =  $file;
                                      $cDir++;
                              }
                              else{
                                      $listFile[$cFile]  =  $file;
                                      $cFile++;
                              }
                      }
              }
              
              //  show  directories
              if(count($listDir)  >  0){
                      sort($listDir);
                      for($j  =  0;  $j  <  count($listDir);  $j++){
                              echo  "
                              <tr>";
                                      $spacer  =  "";
                                      for($l  =  0;  $l  <  $i;  $l++)  $spacer  .=  "&emsp;";
                                      //  create  link
                                      $link  =  "<a  href=\""  .  $_SERVER["PHP_SELF"]  .  "?dir="  .  $dir  .  "/"  .  $listDir[$j]  .  "\">$listDir[$j]</a>";
                                      echo  "<td>"  .  $spacer  .  $link  .  "</td>
                              </tr>";
                              //  list  all  subdirectories  up  to  maxDepth
                              if($i  <  $maxDepth)  showDir($dir  .  "/"  .  $listDir[$j],  $i,  $maxDepth);
                      }
              }
              
              //  show  files
              if(count($listFile)  >  0){
                      sort($listFile);
                      for($k  =  0;  $k  <  count($listFile);  $k++){
                              $spacer  =  "";
                              for($l  =  0;  $l  <  $i;  $l++)  $spacer  .=  "&emsp;";
                              echo  "
                              <tr>
                                      <td>"  .  $spacer  .  $listFile[$k]  .  "</td>
                              </tr>";        
                      }
              }                
              closedir($checkDir);
      }
}

if($_GET["dir"]  ==  ""  ||  !is_dir($_GET["dir"]))  $dir  =  getcwd();
else  $dir  =  $_GET["dir"];
//  replace  backslashes,  not  necessary,  but  better  to  look  at
$dir  =  str_replace("\\",  "/",  $dir);

//  show  parent  path
$pDir  =  pathinfo($dir);
$parentDir  =  $pDir["dirname"];

echo  "<a  href=\""  .  $_SERVER["PHP_SELF"]  .  "\"><h3>Home</h3></a>";
echo  "Current  directory:  "  .  $dir;
echo  "<a  href=\""  .  $_SERVER["PHP_SELF"]  .  "?dir=$parentDir\"><h4>Parent  directory:  $parentDir</h4></a>";

//  Display  directory  content
echo"<table  border=1  cellspacing=0  cellpadding=2>
<tr><th  align=left>File  /  Dir</th>";

//  specifies  the  maxDepth  of  included  subdirectories
//  set  maxDepth  to  0  if  u  want  to  display  the  current  directory
$maxDepth  =  0;
showDir($dir,  -1,  $maxDepth);    
?>  
sandy  at  montana-riverboats  dot  com
30-Sep-2004  01:08  
<?php
/*
**  This  recursive  file  lister  only  slurps  in  one  page  at  time,
**  so  it  doesn't  take  forever  to  load  when  operating  over
**  a  large  system.....comes  with  an  "Up"  link  for  every  page  too.
*/

$PHP_SELF  =  $_SERVER['PHP_SELF'];
$DOCUMENT_ROOT  =  $_SERVER['DOCUMENT_ROOT'];
#  activate  the  next  line  (and  deactivate  the  last)  to
#  use  this  script  in  a  $DOCUMENT_ROOT/~anybody
#  environment.
#$DOCUMENT_ROOT="/home/sandy/public_html/";

$tdir  =  $_GET['dir'];
echo  "tdir==$tdir<br>";
$tparent_path  =  $_GET['parent_path'];
$dbg  =  $_GET['dbg'];

if(!strstr($tdir,  $DOCUMENT_ROOT))
    $tdir  =  getcwd();
if(!strstr($tparent_path,  $DOCUMENT_ROOT))
    $tparent_path  =  $tdir;

if  (!isset  ($tdir))
    {
      $dir  =  getcwd  ();
    }
else
    $dir  =  $tdir;

if  (!isset  ($tparent_path))
    {
      $parent_path  =  $dir;
    }
else
    $parent_path  =  $tparent_path;

echo  "<br>";
if  (!isset  ($tdir))
    {
      $upurl  =  $PHP_SELF;
    }
else
    {
      if  ($parent_path  ==  $DOCUMENT_ROOT)
          $parent_parent_path  =  $parent_path;
      else
          $parent_parent_path  =  dirname  ($parent_path);
      $upurl  =  $PHP_SELF."?dir=".$parent_path."&parent_path=".
                                  $parent_parent_path;
    }

if($dbg==1)
{
    echo  "PHP_SELF:  $PHP_SELF<br>\n";
    echo  "DOCUMENT_ROOT:  $DOCUMENT_ROOT<br>\n";
    echo  "dir:  $dir<br>\n";
    echo  "parent_path:  $parent_path<br>\n";
    echo  "upurl:  $upurl<br>\n";
}

echo  "<a  href=\"$upurl\">  <h3>Up</h3>  </a>\n";
echo  "<h2>$dir</h2>\n";

create_tree  ($dir,  $parent_path);

function
urlFromPath  ($path)
{
    global  $PHP_SELF;
    global  $DOCUMENT_ROOT;
    $prefix  =  "";
    if  (substr  ($path,  0,  1)  !=  "/")
      $prefix  =  "/";
    $url  =  $prefix.ereg_replace  ($DOCUMENT_ROOT,  "",  $path);
    return  $url;
}

function
create_tree  ($dir,  $parent_path)
{
    if  ($handle  =  opendir  ($dir))
      {
          $i  =  0;
          while  (false  !==  ($file  =  @readdir  ($handle)))
      {
          if  ($file  !=  "."  &&  $file  !=  "..")
              {
                  $list[$i]  =  $file;
                  $i++;
              }
      }
          $dir_length  =  count  ($list);
          echo  "<ul>";
          for  ($i  =  0;  $i  <  $dir_length;  $i++)
      {
          global  $PHP_SELF;
          global  $DOCUMENT_ROOT;
          $label  =  $list[$i];
          $test  =  $dir."/".$label;
          $alink  =  $dir."/".ereg_replace("  ","%20",$label);
          if  (!strstr  ($PHP_SELF,  $label))
              {
                  if  (is_dir  ($test))
              {
                  $tmp  =  $PHP_SELF.  "?dir=".$alink."&parent_path=".$dir;
                  $url  =  ereg_replace("  ",  "%20",  $tmp);
                                  echo  "$url<br>\n";
                  echo  "<a  href=\"$url\"><b>$label</b>/</a><br>\n";
              }
                  else
              {
                  $link  =  urlFromPath  ($alink);

                  $label  =  $list[$i];
                  echo
                      "<a  href=\"$link\">".$label."</a><br>\n";
              }
              }
      }
          echo  "</ul>";
          closedir  ($handle);
      }
}

?>  
cnichols  at  nmu  dot  edu
18-Sep-2004  03:03  
Here's  another  recursive  function  that  prints  out  everything  from  the  starting  path  to  the  end.  It  doesn't  have  any  search  function,  but  just  another  example.  I  wrote  it  for  getting  a  quick  hierarchial  view  of  websites  (even  through  Dreamweaver  will  show  it  to  me,  it'd  be  a  chore  to  go  through  each  folder  and  expand  it).

<?php

//  map_dirs(path,level)
//  path,  level  to  start  (start  at  0)

map_dirs("/var/ww/html/",0);

function  map_dirs($path,$level)  {
              if(is_dir($path))  {
                              if($contents  =  opendir($path))  {
                                              while(($node  =  readdir($contents))  !==  false)  {
                                                              if($node!="."  &&  $node!="..")  {
                                                                              for($i=0;$i<$level;$i++)  echo  "    ";
                                                                              if(is_dir($path."/".$node))  echo  "+";  else  echo  "  ";
                                                                              echo  $node."\n";
                                                                              map_dirs("$path/$node",$level+1);
                                                              }
                                              }
                              }
              }
}
  
?>  
MagicalTux  at  FF.st
09-Aug-2004  10:32  
Note  that  the  opendir()  function  will  use  ISO8859-1  characterset  under  windows...

If  you  have  korean,  japanese,  etc..  filenames,  you  won't  be  able  to  open  them.  I  still  didn't  find  any  solution  to  workaround  that.  
dale  dot  liszka  at  gmail  dot  com
07-Aug-2004  12:17  
I  whipped  up  a  little  recursive  directory  searching  function  that  has  been  very  useful.    I  figured  it  belonged  here.    I'm  sure  its  not  the  most  robust  or  creative  code,  but  it  works  for  me.

Note,  you  can  use  strpos  for  simple  matches  or  preg_match  if  you  want  the  power  of  regular  expressions  (however  it  is  a  bit  slower).    I  also  have  it  set  to  use  double  quotes  "\\"  for  WIN32.    change  to  "/"  if  necessary.

It  returns  an  array  of  all  matching  files  with  full  path.

function  search_dir($mask,$dir,$level){
      if($level  >  3){
              return  "Exceeded  max  level  (3)";
      }
      $return_me  =  array();
      if  (is_dir($dir))  {
              if  ($dh  =  opendir($dir))  {
                      while  (($file  =  readdir($dh))  !==  false)  {
                              #echo  "filename:  $file  :  filetype:  "  .  filetype($dir  .  $file)  .  "  level:  $level\n";
                              if(is_dir($dir."\\".$file)  and  $file  !=  '.'  and  $file  !=  '..'){
                                      $test_return  =  search_dir($mask,$dir."\\".$file,$level+1);
                                      if(is_array($test_return)){
                                              $temp  =  array_merge($test_return,$return_me);
                                              $return_me  =  $temp;
                                      }
                                      if(is_string($test_return)){
                                              array_push($return_me,$test_return);
                                      }
                              #}  else  if(strpos($file,$mask)  !==  FALSE){    #A  bit  faster,  but  you  can't  use  regexs!
                              }  else  if(preg_match($mask,$file)){
                                      array_push($return_me,$dir."\\".$file);
                              }
                      }
                      closedir($dh);
              }
      }
      return  $return_me;
}  
Cabal  at  CnCWorld  dot  org
28-Mar-2004  11:21  
I  had  problems  getting  it  to  work  because  I'm  not  the  best  at  PHP,  but  there  IS  a  way  to  use  opendir  to  list  things  in  alphabetical  order.  I'm  using  it  for  my  university  project.  All  you  have  to  do  is  read  the  filenames  into  an  array,  sort  the  array  and  then  do  what  you  want  with  the  filenames....  like  this....

So  that  you  know  what  all  my  variables  mean  in  this  -  $stats  is  the  folder  that  it  looks  in  for  the  files  -  for  example
?stats=images
would  look  in  the  images  folder

Obviously  you  will  want  to  modify  it  so  it  fits  your  needs,  but  I  thought  you  guys  would  want  this  -  especially  if  your  server  doesnt  have  the  latest  version  of  php.

===========================

<?php  
$i  =  0;
$arraycount  =  0;
$home="/home/cabal/public_html/b146/admin/$stats";

if  ($stats)
{
      $dircheck="/home/cabal/public_html/b146/admin/$stats";
      if  (is_dir($dircheck))
      {
              if  ($handle  =  opendir($home))
              {
                      while  (false  !==  ($file  =  readdir($handle)))  
                      {  
                                      if  ($file  !=  "."  &&  $file  !=  "..")  
                      {
                      $path  =  "$home/$file";
                      $extension  =  array_pop(explode('.',  basename($path)));
                      $filearray[$i]  =  $file;
                      $i++;
                      }  
                      }
                      }
                      closedir($handle);  
              
      }
      else
      {
      echo  "INCORRECT  SELECTION";
      }

}

else

{
echo  "NOTHING  SELECTED";
}
echo  "&nbsp;";

echo("<table  width='100%'  border='1'><tr><td><b><font  color='#ff0000'>");
echo("$stats  :  Log  File");
echo("</b></font></td><td><font  color='#FF0000'><b>Page  Views</b></font></td></tr>");
sort($filearray);
reset($filearray);
while  (list($key,  $val)  =  each($filearray))
{
      $includearray  =  "$home/$filearray[$key]";
      echo("<tr><td>");
      echo("$val");
      echo("</td><td>");
      include($includearray);
      echo("</td></tr>");
      
}
echo("</table>");

?>  

9050 view

4.0 stars