[英]Get all opened resource handle in PHP
I have been working with a PHP application, which uses the methods fopen
and ftp_connect
a lot. 我一直在使用PHP应用程序,它使用方法
fopen
和ftp_connect
很多。 One of the servers where the application is running throw a Fatal Exception
, when too many files are opened, Hence I needed to find all classes which used that methods and refactored them so that they close the file handles afterwards with fclose
and ftp_close
. 运行应用程序的服务器之一会在打开太多文件时抛出
Fatal Exception
,因此我需要找到所有使用该方法并重构它们的类,以便之后使用fclose
和ftp_close
关闭文件句柄。
By doing this I wanted to add an integration test afterwards which tracks down all opened resources so that something like this would not happen again. 通过这样做,我想在之后添加一个集成测试,跟踪所有打开的资源,以便这样的事情不会再发生。
Is there a way to do this in PHP? 有没有办法在PHP中执行此操作?
You can obtain desired result using get_defined_vars()
, gettype()
and — optionally — get_resource_type()
: 您可以使用
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 );
}
Assuming you have these opened resources: 假设您拥有这些已打开的资源:
$handle = fopen( '/Your/File/Path' );
$ftp1 = ftp_connect ( 'ftp.site1.com' );
$ftp2 = ftp_connect ( 'ftp.site2.com' );
Above code will output: 上面的代码将输出:
stream : 1
FTP Buffer : 2
PHP 7.0.0引入了一个获取资源的函数,名为get_resources()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.