php 使用文件句柄获取文件名(或删除文件)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5144583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:56:02  来源:igfitidea点击:

Getting filename (or deleting file) using file handle

phpfile

提问by ts.

Is there a possibility to obtain filename from file handle? Or how can I delete file having only a handle?

是否有可能从文件句柄中获取文件名?或者如何删除只有句柄的文件?

回答by lion.vollnhals

There is stream_get_meta_data. It works for a stream that you get from tmpfile(). If you call it on a regular file pointer then you might only get the basename.

stream_get_meta_data。它适用于您从 tmpfile() 获得的流。如果您在常规文件指针上调用它,那么您可能只会获得基本名称。

$meta_data = stream_get_meta_data($stream_or_file_pointer);
$filename = $meta_data["uri"];
echo $filename;

Example for tmpfile():

tmpfile() 示例:

"/private/var/folders/v3/n54x13jx5v7610fw9dm0wcxm0000gn/T/phpCJvevP"

Example for fopen("somefile", "r"):

fopen("somefile", "r") 示例:

"test"

回答by Gordon

Nyes. Afaik there is no function in PHP to that directly. Buton Linux, you can do

是的。Afaik 在 PHP 中没有直接的功能。但是在 Linux 上,你可以这样做

$fp = fopen('somefile', 'r');
$stat = fstat($fp);
$inode = $stat['ino'];
system("find -inum $inode", $result);
echo $result;

This is untested so it might need tweaking.

这是未经测试的,因此可能需要调整。

EDITApparently, there isa simpler solution.

编辑显然,有一个简单的解决方案

回答by Greg

To achieve this, you will need to create a wrapper that stores the file name. A file handle has no context of the filename it was created from.

为此,您需要创建一个存储文件名的包装器。文件句柄没有创建它的文件名的上下文。

回答by diyism

A clean method to use temporary file:

使用临时文件的干净方法:

<?
$tmp=array_search('uri', @array_flip(stream_get_meta_data($GLOBALS[mt_rand()]=tmpfile())));
file_put_contents($tmp, 'hello');
echo file_get_contents($tmp);
?>

without need to fclose the tmp file, it will be deleted while the php ends.

不需要关闭tmp文件,在php结束时它会被删除。