好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

php 判断目录下是否有文件存在 - php文件操作

php 判断目录下是否有文件存在

今天在写上传图片作为封面的时候,为了避免重复的上传封面而导致,封面图片乱设置,就百度出了判断文件夹是否为空的代码.

<?php   $dir  = opendir( '1' );  $ml  = 0;  while  (( $file  = readdir( $dir )) !== false)    {  $cs  =  $ml ++;    if ( $cs  ==  "2" ){ echo   "有文件" ;}    }     closedir ( $dir );  ?> 

获取文件夹1的目录,因为函数会获取.和.. 本身和上级目录都显示出来,这样就循环成了1这样的结果也就是文件夹为空,如果循环到2的时候就会显示出目录下的文件.

例子代码如下:

<?php  function  is_empty_dir( $dir_path )  {  if  (! is_dir ( $dir_path )){  echo  [文件夹不存在];  return  true; //www.phpfensi.com   }  $dir  = opendir( $dir_path );  $is_empty  = true;  while  ( $file  = readdir( $dir )){  if ( $file  == ‘.’ ||  $file  == ‘..’)  continue ;  $is_empty  = false;  break ;  }  closedir ( $dir );  return   $is_empty ;  }  ?> 

例子代码如下:

<?php  $root  = dirname( __FILE__ );  $root  =  str_replace ( "\", " /",  $root );  $path  =  $root . '/test/' ;  $isempty  = file_exit();  //检查目录是否为空   function  file_exit( $filelastname  =  '' ){  global   $path ;  if ( $filelastname  !=  '' ){      $handle  = opendir( $path . $filelastname );  } else {      $handle  = opendir( $path );   }  while  (false !== ( $file  = readdir( $handle ))) {      if ( $file  ==  '.'  ||  $file  ==  '..' ){       continue ;     }      $file_array [] =  $file ;  }  if ( $file_array  == NULL){ //没有文件       closedir ( $handle );      return  false;  }  closedir ( $handle );  return  true; //有文件   }  ?> 

查看更多关于php 判断目录下是否有文件存在 - php文件操作的详细内容...

  阅读:81次