Get filesystem path from a PHP streamwrapper?

半世苍凉 提交于 2019-12-14 03:55:29

问题


If I have a file in a php streamwrapper, such as "media://icon.png" how can I get it to tell me the filesystem path of that file, assuming it's on a filesystem?

I looked on the documentation page but didn't see a method to return the streamwrapper path.


回答1:


The StreamWrapper class represents generic streams. Because not all streams are backed by the notion of a filesystem, there isn't a generic method for this.

If the uri property from stream_get_meta_data isn't working for your implementation, you can record the information during open time then access it via stream_get_meta_data. Example:

class MediaStream {
    public $localpath = null;

    public function stream_open($path, $mode, $options, &$opened_path)
    {
        $this->localpath = realpath(preg_replace('+^media://+', '/', $path));

        return fopen($this->localpath, $mode, $options);
    }
}

stream_wrapper_register('media', 'MediaStream');

$fp   = fopen('media://tmp/icon.png', 'r');
$data = stream_get_meta_data($fp);
var_dump(
    $data['wrapper_data']->localpath
);

Of course, there's always a brute force approach: after creating your resource, you can call fstat, which includes the device and inode. You can then open that device, walk its directory structure, and find that inode. See here for an example.



来源:https://stackoverflow.com/questions/30985093/get-filesystem-path-from-a-php-streamwrapper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!