我想将一个原始的HTTP数据包发送到网络服务器并收到它的响应,但我无法找到一种方法来实现它。我不熟悉套接字和我找到的每个链接使用套接字发送udp数据包。任何帮助都会很棒。
答案 0 :(得分:7)
<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.example.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
与fsockpen
建立与服务器的连接。 $out
保存随后使用frwite
发送的HTTP请求。然后使用fgets
读取HTTP响应。
答案 1 :(得分:3)
如果您只想执行GET请求并接收响应正文,那么大多数文件函数都支持使用url:
<?php
$html = file_get_contents('http://google.com');
?>
<?php
$fh = fopen('http://google.com', 'r');
while (!feof($fh)) {
$html .= fread($fh);
}
fclose($fh);
?>
不仅仅是简单的GET,请使用curl(你必须将它编译成php)。使用curl,您可以执行POST和HEAD请求,以及设置各种标题。
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://google.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec($ch);
?>
答案 2 :(得分:2)
cURL比实现客户端HTTP更容易。您所要做的就是设置几个选项,cURL处理其余的选项。
$curl = curl_init($URL);
curl_setopt_array($curl,
array(
CURLOPT_USERAGENT => 'Mozilla/5.0 (PLAYSTATION 3; 2.00)',
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_USERPWD => 'User:Password',
CURLOPT_RETURNTRANSFER => True,
CURLOPT_FOLLOWLOCATION => True
// set CURLOPT_HEADER to True if you want headers in the result.
)
);
$result = curl_exec($curl);
如果需要设置cURL不支持的标头,请使用CURLOPT_HTTPHEADER选项,传递一组额外的标头。如果需要解析标头,请将CURLOPT_HEADERFUNCTION设置为回调。阅读curl_setopt
的文档以获取更多选项。