如何使用file_get_contents搜索流?

时间:2013-03-15 14:44:02

标签: php stream file-get-contents

我正在使用PHP来运行web服务。其中一个网址需要从POST正文中获取几张图片。我目前正在使用fopen / fread解决方案:

$size1 = intval($_REQUEST['img1']);
$size2 = intval($_REQUEST['img2']);
$sizeToRead = 4096;
$datas1 = null;
$datas2 = null;

$h = fopen('php://input','r+');
while($size1 > 0) {
    if($sizeToRead > $size1)
        $sizeToRead = $size1;

    $datas1 .= fread($h,$sizeToRead);
    $size1 -= $sizeToRead;
}
fclose($h);

file_put_contents('received1.png',$datas1);
//Same thing for the second image

此解决方案运行正常,但我尝试使用file_get_contents()使其更具可读性:

file_put_contents('received1.png',file_get_contents('php://input',false,null,0,$size1));

但它给了我一个错误:

  

file_get_contents()流不支持搜索   file_get_contents()无法在流

中寻找21694

甚至可以在流中寻找?也许通过将第三个参数更改为其他参数?

如果没有,是否有办法让我的代码更优雅/更有效?

感谢。

1 个答案:

答案 0 :(得分:2)

引用manual

  

注意:使用php://输入打开的流只能读取一次; 流不支持搜索操作。但是,根据SAPI实现,可能会打开另一个php://输入流并重新开始读取。只有在保存了请求正文数据后才能执行此操作。通常,这是POST请求的情况,但不是其他请求方法,例如PUT或PROPFIND。

(我的重点)