如何检查PHP流资源是否可读或可写? [英] How to check if a PHP stream resource is readable or writable?

查看:101
本文介绍了如何检查PHP流资源是否可读或可写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,如何检查流资源(或文件指针,句柄或任何您想调用的资源)是否可读或可写?例如,如果您遇到对资源的​​打开或创建方式一无所知的情况,如何检查它是否可读?以及如何检查它是否可写?

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 situation where you know nothing about how the resource was opened or created, how do you check if it's readable? And how do you check if it's writable?

根据我所做的测试(仅使用PHP 5.3.3的常规文本文件进行测试), fread() 不会在任何级别上引发任何错误.它只返回一个空字符串,但它也对一个空文件执行此操作.理想情况下,最好进行不修改资源本身的检查.通过尝试从资源中读取来测试它是否可读,将会改变指针的位置.

Based on the testing that I've done (just with regular text files using PHP 5.3.3), fread() does not throw any errors at any level when the resource is not readable. It just returns an empty string, but it also does that for an empty file. And ideally, it would be better to have a check that doesn't modify the resource itself. Testing if a resource is readable by trying to read from it will change the position of the pointer.

相反, fwrite() 不会在任何地方抛出任何错误资源不可写时的级别.它只是返回零.这稍微有用一点,因为如果您尝试向文件中写入一定数量的字节,而fwrite()返回零,则说明出了点问题.但这仍然不是理想的方法,因为在我需要写它之前最好先知道它是否可写,而不是尝试写它然后看看是否失败.

Conversely, fwrite() does not throw any errors at any level when the resource is not writable. It just returns zero. This is slightly more useful, because if you were trying to write a certain number of bytes to a file and fwrite() returns zero, you know something went wrong. But still, this is not an ideal method, because it would be much better to know if it's writable before I need to write to it rather than trying to write to it and see if it fails.

此外,理想情况下,检查应适用于任何类型的流资源,而不仅仅是文件.

Also, ideally, the check should work on any sort of stream resource, not just files.

这可能吗?像这样的东西存在吗?我一直找不到任何有用的东西.预先感谢您的回答.

Is this possible? Does anything like this exist? I have been unable to find anything useful. Thanks in advance for your answers.

推荐答案

非常简单.只需从脚本中调用 stream_get_meta_data($resource) ,然后检查返回值的mode数组元素:

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

这篇关于如何检查PHP流资源是否可读或可写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆