PHP如何使用closeir()函数?代码示例

2021年3月31日16:34:13 发表评论 577 次浏览

PHP中的closedir()函数是一个内置函数, 用于关闭目录句柄。将要关闭的目录句柄作为参数发送到closedir()函数, 并且closedir()关闭目录句柄。必须预先通过opendir()函数打开目录句柄。

语法如下:

closedir($dir_handle)

使用的参数:PHP中的closedir()函数仅接受一个参数, 如下所述。

  • $ dir_handle:这是一个可选参数, 用于指定先前使用opendir()打开的目录句柄资源。如果未指定此参数, 则假定由opendir()打开的最后一个链接由closedir()关闭。

返回值:它不返回任何值。

错误与异常:

  1. 作为参数发送到closedir()函数的目录句柄必须事先由opendir()函数打开。
  2. 如果未指定dir_handle参数, 则假定由opendir()打开的最后一个链接由closeir()函数关闭。

以下程序说明了closedir()函数:

程序1:

<?php
  
// Opening a directory
$dir_handle = opendir( "/user/gfg/docs/" );
  
if ( is_resource ( $dir_handle ))
{ 
     echo ( "Directory Opened Successfully." );
  
     // closing the directory
     closedir ( $dir_handle );
}
else
{
     echo ( "Directory Cannot Be Opened." );
} 
  
?>

输出如下:

Directory Opened Successfully.

程序2:

<?php
  
// opening a directory and reading its contents
$dir_handle = opendir( "user/gfg/sample.docx" );
  
if ( is_resource ( $dir_handle )) 
{ 
     while (( $file_name = readdir( $dir_handle )) == true) 
     { 
         echo ( "File Name: " . $file_Name );
         echo "<br>" ; 
     } 
  
     // closing the directory
     closedir ( $dir_handle );
}
else
{
     echo ( "Directory Cannot Be Opened." );
}
  
?>

输出如下:

File Name: sample.docx

参考: http://php.net/manual/en/function.closedir.php


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: