【发布时间】:2018-08-31 13:08:09
【问题描述】:
是否有一些fopen 将在大多数 PHP 安装中成功打开的 url/流? /dev/null 在某些系统上不可用或无法打开。像php://temp 这样的东西应该是一个相当安全的选择,对吧?
此代码的应用程序保证文件资源,而不是bool|resource 与fopen 的混合文件类型:
/**
* @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;
}
在具有严格类型的 PHP 7 中,上述函数应保证资源并避免布尔值。我知道resources are not official types,但仍然希望尽可能地保证类型安全。
【问题讨论】:
-
php://temp应该可以正常工作,但可能不是实际记录事物的最佳位置,因为它被设计为瞬态的。它实际上根本不会触及文件系统,除非您写入超过定义的内存限制(默认为 2mb),因此脚本一退出它就会丢失。tmpfile可能是另一种选择。 -
看看
sys_get_temp_dir,它应该适用于几乎所有运行 PHP 的操作系统:secure.php.net/manual/en/function.sys-get-temp-dir.php -
如果记录错误是这里的目的,那么为什么不使用php.net/manual/en/function.error-log.php 开始呢?使用 message_type=0 时,这已经采用本地设置来考虑应该记录哪里错误。
-
Do some error logging here评论只是为了表明我想要一些打开文件失败的信号。我将编辑示例。
标签: php stream disaster-recovery