6

我想向网络服务器发送一个原始的 http 数据包并接收它的响应,但我找不到一种方法来做到这一点。我对套接字没有经验,我发现的每个链接都使用套接字发送 udp 数据包。任何帮助都会很棒。

4

3 回答 3

9

看看fsockopen手册页中的这个简单示例:

<?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保存 HTTP 请求,然后使用frwite. 然后使用 读取 HTTP 响应fgets

于 2009-09-22T23:10:33.047 回答
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);

?>
于 2009-09-23T02:18:16.250 回答
2

cURL is easier than implementing client side HTTP. All you have to do is set a few options and cURL handles the rest.

$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);

If you need to set a header that cURL doesn't support, use the CURLOPT_HTTPHEADER option, passing an array of additional headers. Set CURLOPT_HEADERFUNCTION to a callback if you need to parse headers. Read the docs for curl_setopt for more options.

于 2009-09-23T07:20:50.880 回答