php 先fseek in stream 然后fread?
php first fseek in stream then fread?
我正在试验一些 php 文件/流功能。我有恐惧的麻烦。
此数据被发送到 php 脚本:
baz=bomb&foo=bar&baz=bomb&foo=bar&foo=bar&baz=bomb
并且该脚本运行此代码:
<php
$fp = fopen("php://input", "rb");
fseek($fp, 3, SEEK_SET);
echo "<br>ftell: ".ftell($fp)."<br>";
echo "<br>fread(resource, 4): ".fread($fp, 4)."<br>";
fclose($fp);
输出显示:
ftell: 3
fread(resource, 4): baz=
我期望它显示的是:
=bom
为什么fread好像是先把指针设置到流的开头,然后再读取?在流中寻找并且无法从某个位置读取有什么意义?
我使用的php版本是:
windows 机器上的 7.0.8。
这就是问题的答案,我希望许多人能从中受益:
当使用 fseek 时,ftell 似乎会告诉您指针在流中的位置。但事实并非如此。流中的指针不能通过 fseek 函数移动,这很奇怪。正如 Starson Hochschild 指出的那样,这是因为底层流没有实现查找处理程序。
所以另一种方法是读取 $_POST。但是大内容呢?
有一个名为 php://temp 的流。您放入其中的前两个 MB 将进入您电脑的内存中。更多数据将进入您电脑上的临时文件。
所以你可以像这样使用它:
$tempStream = fopen("php://input", "rb");
$stream = fopen("php://temp", "w+b");
$size = 0;
while (!feof($in)) $size += fwrite($stream,fread($tempStream,8192)); //Copy the php://input stream to the seekable php://temp stream. $size will contain the size in bytes of the $stream resource.
fclose($tempStream);
//Do your next fread's, fseek's, ftell's etc here on the $stream resource.
fclose($stream);
我正在试验一些 php 文件/流功能。我有恐惧的麻烦。
此数据被发送到 php 脚本:
baz=bomb&foo=bar&baz=bomb&foo=bar&foo=bar&baz=bomb
并且该脚本运行此代码:
<php
$fp = fopen("php://input", "rb");
fseek($fp, 3, SEEK_SET);
echo "<br>ftell: ".ftell($fp)."<br>";
echo "<br>fread(resource, 4): ".fread($fp, 4)."<br>";
fclose($fp);
输出显示:
ftell: 3
fread(resource, 4): baz=
我期望它显示的是:
=bom
为什么fread好像是先把指针设置到流的开头,然后再读取?在流中寻找并且无法从某个位置读取有什么意义?
我使用的php版本是: windows 机器上的 7.0.8。
这就是问题的答案,我希望许多人能从中受益:
当使用 fseek 时,ftell 似乎会告诉您指针在流中的位置。但事实并非如此。流中的指针不能通过 fseek 函数移动,这很奇怪。正如 Starson Hochschild 指出的那样,这是因为底层流没有实现查找处理程序。
所以另一种方法是读取 $_POST。但是大内容呢?
有一个名为 php://temp 的流。您放入其中的前两个 MB 将进入您电脑的内存中。更多数据将进入您电脑上的临时文件。
所以你可以像这样使用它:
$tempStream = fopen("php://input", "rb");
$stream = fopen("php://temp", "w+b");
$size = 0;
while (!feof($in)) $size += fwrite($stream,fread($tempStream,8192)); //Copy the php://input stream to the seekable php://temp stream. $size will contain the size in bytes of the $stream resource.
fclose($tempStream);
//Do your next fread's, fseek's, ftell's etc here on the $stream resource.
fclose($stream);