简体   繁体   English

PHP如何发送原始HTTP数据包

[英]PHP How To Send Raw HTTP Packet

I want to send a raw http packet to a webserver and recieve its response but i cant find out a way to do it. 我想将一个原始的HTTP数据包发送到网络服务器并收到它的响应,但我无法找到一种方法来做到这一点。 im inexperianced with sockets and every link i find uses sockets to send udp packets. 我不熟悉套接字和我找到的每个链接使用套接字发送udp数据包。 any help would be great. 任何帮助都会很棒。

Take a look at this simple example from the fsockopen manual page : 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);
}
?>

The connection to the server is established with fsockpen . 使用fsockpen建立与服务器的连接。 $out holds the HTTP request that's then send with frwite . $out保存HTTP请求,然后用frwite发送。 The HTTP response is then read with fgets . 然后使用fgets读取HTTP响应。

If all you want to do is perform a GET request and receive the body of the response, most of the file functions support using urls: 如果您只想执行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);

?>

For more than simple GETs, use curl (you have to compile it into php). 不仅仅是简单的GET,请使用curl(你必须将它编译成php)。 With curl you can do POST and HEAD requests, as well as set various headers. 使用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);

?>

cURL is easier than implementing client side HTTP. cURL比实现客户端HTTP更容易。 All you have to do is set a few options and cURL handles the rest. 您所要做的就是设置几个选项,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);

If you need to set a header that cURL doesn't support, use the CURLOPT_HTTPHEADER option, passing an array of additional headers. 如果需要设置cURL不支持的标头,请使用CURLOPT_HTTPHEADER选项,传递一组额外的标头。 Set CURLOPT_HEADERFUNCTION to a callback if you need to parse headers. 如果需要解析标头,请将CURLOPT_HEADERFUNCTION设置为回调。 Read the docs for curl_setopt for more options. 阅读curl_setopt的文档以获取更多选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM