gpt4 book ai didi

PHP fsockopen()/fread() 返回困惑的数据

转载 作者:行者123 更新时间:2023-12-04 07:04:47 25 4
gpt4 key购买 nike

我用 fsockopen() 和 fread() 读取了一些 URL,我得到了这种数据:

      <li
10
></li>
<li
9f
>asd</li>

d
<li
92

这完全搞砸了O_O

--

在使用 file _ get _ contents() 函数时,我得到了这种数据:
<li></li>
<li>asd</li>

哪个是对的!那么,到底哪里错了?我在我的 windows 服务器和 linux 服务器上试过,两者的行为都是一样的。他们甚至没有相同的 PHP 版本。

--

我的 PHP 代码是:
$fp = @fsockopen($hostname, 80, $errno, $errstr, 30);
if(!$fp){
return false;
}else{
$out = "GET /$path HTTP/1.1\r\n";
$out .= "Host: $hostname\r\n";
$out .= "Accept-language: en\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);

$data = "";
while(!feof($fp)){
$data .= fread($fp, 1024);
}
fclose($fp);

感谢任何帮助/提示,​​现在一整天都在想:/

哦,我不能使用 fopen() 或 file_get_contents() 因为我的脚本运行的服务器没有启用 fopen 包装器> __ <

我真的很想知道如何解决这个问题,只是出于好奇。而且我认为无论如何我都不能在此服务器上使用任何额外的库。

最佳答案

关于您的“奇怪数据”问题,这可能是因为您从中请求数据的服务器正在以分 block 模式传输数据。

在浏览器中调用相同的 URL 时,您可以查看 HTTP header ;这些标题之一可能是这样的:

Transfer-encoding: chunked

报价 wikipedia's article on that matter :

Each non-empty chunk starts with the number of octets of the data it embeds (size written in hexadecimal) followed by a CRLF (carriage return and line feed), and the data itself. The chunk is then closed with a CRLF. In some implementations, white space characters (0x20) are padded between chunk-size and the CRLF.

The last chunk is a single line, simply made of the chunk-size (0), some optional padding white spaces and the terminating CRLF. It is not followed by any data, but optional trailers can be sent using the same syntax as the message headers.

The message is finally closed by a final CRLF combination.



这看起来接近你得到的......所以我猜这就是问题所在。

据我记得,curl 知道如何处理这个问题——所以,最简单的方法是使用 curl而不是 fsockopen 之类的

并且使用 curl 通常比使用套接字更好:它将处理您可能遇到的许多问题;像这个 ;-)

另一个想法是,如果您的服务器上没有启用 curl,则可以使用一些已经存在的基于 fsockopen 的库——希望它已经为您处理了这些事情。

例如,我曾与 Snoopy 合作过。一些时间 ;也许它已经知道如何处理?
(不确定:您必须自己测试 - 或查看文档以了解是否可以)

不过,如果您想自己解决 HTTP 协议(protocol)的奥秘……那么,祝您好运!

关于PHP fsockopen()/fread() 返回困惑的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1279652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com