G
G
Gesper2010-12-02 13:39:18
PHP
Gesper, 2010-12-02 13:39:18

PHP. How to get filename from open file handle

Problem. There is a function that generates some filename, writes it to the database and executes
return fopen($filename);

And now the problem arose, how to get the name of the open file from the returned handler. I did not find an adequate way to do this using PHP.

PS. Yes, the question is purely theoretical, I will most likely solve the problem by rewriting the function so that it returns a name in addition to the handler.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
G
Gesper, 2010-12-02
@Gesper

I asked the question myself, and I will answer it myself. I had to dig into the manuals, but the answer was found.
fopen returns a resource of type stream. And among the functions working with streams, there was a stream_get_meta_data function that returns an associative array. This array contains the uri parameter, which contains the desired file name with which our handler is associated.

L
lafayette, 2010-12-02
@lafayette

As far as I know, this is not possible.

E
Eugene, 2010-12-02
@immaculate

On Unix systems, a file and its name are distinct entities, so it's not possible. More precisely, it is possible to traverse the entire directory tree, starting with /, and look for a name that matches the inode, but this is a completely suboptimal solution.

A
Alexey, 2010-12-02
@alexxxst

It is possible in Linux like this:
/proc/PID/fd/@FD is a link to your file, for example:

[email protected]:/# ps aux | grep nginx
root 3267 0.0 0.0 28724 824 ? Ss Sep22 0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf#
...
[email protected]:/# cd /proc/3267/fd
[email protected]:/proc/3267/fd# ls -l
l-wx------ 1 root root 64 2010-12-02 14:52 2 -> /var/log/nginx/error.log
...

2 - here - the file descriptor is numeric, you can immediately see which file it points to ...
I haven't tried it in PHP, but it's easy in the console.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question