How to check if a PHP stream resource is readable or writable?

前端 未结 2 1507
后悔当初
后悔当初 2020-12-16 12:41

In PHP, how do I check if a stream resource (or file pointer, handle, or whatever you want to call them) is either readable or writable? For example, if you\'re faced with a

相关标签:
2条回答
  • 2020-12-16 13:07

    Quite simple. Just call stream_get_meta_data($resource) from your script, then check the mode array element of the return value:

    $f = fopen($file, 'r');
    $meta = stream_get_meta_data($f);
    var_dump($meta['mode']); // r
    

    And if you want to know if the underlying data is writable:

    var_dump(is_writable($meta['uri'])); // true if the file/uri is writable
    
    0 讨论(0)
  • 2020-12-16 13:16

    Okay, so this may not be the best solution, but I think it suffices, given that there's nothing in PHP to do this automagically.

    For the first step, you'll get the inode of the resource from the file, and then read the filename:

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

    Taken directly from this question about finding the filename from a filehandle.

    Now that you have the filename (in $result) you can do a fileperms($result) on it to get the permissions out.

    Note that fileperms() returns an int, and the documentation does the magic (actually just treating the int as an octal) of retaining that leading 0 (e.g. 0755).

    Also note that the documentation does the magic of converting that int into a nice string like -rw-r--r--

    0 讨论(0)
提交回复
热议问题