获取 PHP 中所有打开的资源句柄


Get all opened resource handle in PHP

我一直在使用一个PHP应用程序,它使用的方法fopenftp_connect很多。当打开太多文件时,运行应用程序的服务器之一会抛出Fatal Exception,因此我需要找到所有使用该方法的类并重构它们,以便它们之后用 fcloseftp_close 关闭文件句柄。

通过这样做,我想在之后添加一个集成测试,以跟踪所有打开的资源,这样的事情就不会再发生。

有没有办法在 PHP 中做到这一点?

您可以使用

get_defined_vars()gettype()和(可选)get_resource_type()获得所需的结果:

$resources = array();
foreach( get_defined_vars() as $key => $val )
{
    if( 'resource' == gettype( $val ) )
    {
        $resources[ get_resource_type( $val ) ][] = $key;
    }
}
foreach( $resources as $type => $res )
{
    echo sprintf( '%- 20s: % 3d%s', $type, count($res), PHP_EOL );
}

假设您有这些打开的资源:

$handle = fopen( '/Your/File/Path' );
$ftp1   = ftp_connect ( 'ftp.site1.com' );
$ftp2   = ftp_connect ( 'ftp.site2.com' );

上面的代码将输出:

stream              :   1
FTP Buffer          :   2

>PHP 7.0.0引入了一个获取资源的函数,称为get_resources()