dqls67891 2013-03-15 14:44
浏览 115
已采纳

如何使用file_get_contents搜索流?

I'm using PHP to run a webservice. One of the url need to get couple images from the POST body. I currently using a fopen/fread solution :

$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

This solution works fine , but i'm trying to make it more readable by using file_get_contents() :

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

But it's give me an error :

file_get_contents() stream does not support seeking
file_get_contents() Failed to seek to position 21694 in the stream

Is that even possible to seek in a stream ? Maybe by changing the third parameter to something else ?

If not , is there way to make my code more elegant / efficient ?

Thanks.

  • 写回答

1条回答 默认 最新

  • doubao6936 2013-03-15 14:57
    关注

    Quoting from the manual:

    Note: A stream opened with php://input can only be read once; the stream does not support seek operations. However, depending on the SAPI implementation, it may be possible to open another php://input stream and restart reading. This is only possible if the request body data has been saved. Typically, this is the case for POST requests, but not other request methods, such as PUT or PROPFIND.

    (my emphasis)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?