PHP使用socket发送HTTP请求的方法

原创
2016-07-29 09:03:45 801浏览

本文实例讲述了PHP使用socket发送HTTP请求的方法。分享给大家供大家参考,具体如下:

socket方式:

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec"=>20, "usec"=>0));
socket_connect($socket, 'www.baidu.com', 80);
//里面的换行代表 \r\n 注意拷贝的代码后面可能有空格
$http = <<

fsockopen方式:

$fp = fsockopen("www.baidu.com", 80, $errno, $errstr, 30);
if (!$fp) {
  echo "$errstr ($errno)
\n"; } else { $out = "GET / HTTP/1.1\r\n"; $out .= "Host: www.baidu.com\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $http); while (!feof($fp)) { echo fgets($fp, 128); } fclose($fp); }

原始socket方式:

$fp = stream_socket_client("tcp://www.baidu.com:80", $errno, $errstr, 30);
if (!$fp) {
  echo "$errstr ($errno)
\n"; } else { $http = <<

stream 方式(get):

$http = <<array(
        'header' => $http,
        'timeout'=>1, //超时 秒
        'method' => 'GET', //默认方式
         'protocol_version' => '1.1', //默认为 1.0
    ),
);
//参数格式参考 http://php.net/manual/zh/context.http.php
//curl方式的格式可以参考; http://php.net/manual/zh/context.curl.php
$context = stream_context_create($hdrs);
echo file_get_contents('http://www.baidu.com', 0, $context);

stream 方式 post:

$postdata = http_build_query(array('act'=>'save', 'id'=>387171));
$http = <<array(
        'header' => $http,
        'timeout'=>1, //超时 秒
        'method' => 'POST',
        'content' => $postdata,
         'protocol_version' => '1.1', //默认为 1.0
    ),
);
//参数格式参考 http://php.net/manual/zh/context.http.php
//curl方式的格式可以参考; http://php.net/manual/zh/context.curl.php
$context = stream_context_create($hdrs);
echo file_get_contents('http://test.cm/song.php', 0, $context);

注意:http1.1 中必须包含 Host 头, 而 http1.0中则可以没有

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php socket用法总结》、《PHP基本语法入门教程》、《PHP错误与异常处理方法总结》及《php常用函数与技巧总结》

希望本文所述对大家PHP程序设计有所帮助。

以上就介绍了PHP使用socket发送HTTP请求的方法,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。