PHP 上是否有保证的文件资源?

Is there a guaranteed file resource on PHP?

是否有一些 url/stream fopen 可以在大多数 PHP 安装中成功打开? /dev/null 在某些系统上不可用或无法打开。 php://temp 之类的东西应该是一个相当安全的赌注,对吧?

此代码的应用程序保证文件资源,而不是 bool|resourcefopen:

的混合文件类型
/**
 * @return resource
 */
function openFileWithResourceGuarantee() {
    $fh = @fopen('/write/protected/location.txt', 'w');
    if ( $fh === false ) {
        error_log('Could not open /write/protected/location.txt');
        $fh = fopen('php://temp');
    }
    return $fh;
}

在 PHP7 严格类型中,上述函数应保证资源并避免布尔值。我知道 ,但仍希望尽可能保持类型安全。

php://memory 应该是普遍可用的。

如果您需要流来写入错误,为什么不写入 php://stderr

来自文档的示例:

When logging to apache on windows, both error_log and also trigger_error result in an apache status of error on the front of the message. This is bad if all you want to do is log information. However you can simply log to stderr however you will have to do all message assembly:

LogToApache($Message) {
        $stderr = fopen('php://stderr', 'w'); 
        fwrite($stderr,$Message); 
        fclose($stderr); 
}

注意:php://stderr 有时与 php://stdout 相同,但并非总是如此。

对于流,请参阅:http://php.net/manual/en/wrappers.php.php

Something like php://temp should be a fairly safe bet, right?

正如@weirdan 已经指出的那样,php://memory 可能更安全,因为它甚至不需要创建任何文件。内存访问必须是可能的。来自文档:

php://memory and php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the sys_get_temp_dir() function.

不确定这是否完全回答了您的问题,但它是否引导您走向正确的方向?