Home  >  Article  >  Backend Development  >  How to send HTTP request through socket in PHP

How to send HTTP request through socket in PHP

墨辰丷
墨辰丷Original
2018-06-05 09:43:001552browse

This article mainly introduces how sockets in PHP send HTTP requests. Interested friends can refer to it. I hope it will be helpful to everyone.

socket method

$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 Method :

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

##stream Method (get):

$http = <<array(
        'header' => $http,
        'timeout'=>1, //超时 秒
        'method' => 'GET', //默认方式
         'protocol_version' => '1.1', //默认为 1.0
    ),
);
$context = stream_context_create($hdrs);
echo file_get_contents('http://www.baidu.com', 0, $context);

stream method 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
    ),
);
$context = stream_context_create($hdrs);
echo file_get_contents('http://test.cm/song.php', 0, $context);

Note: The Host header must be included in http1.1, but it does not need to be included in http1.0

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php method to implement image uploading and cutting functions based on CodeIgniter

Detailed explanation of php metaphone() function and php localeconv() function examples

php image upload class and calling method

##

The above is the detailed content of How to send HTTP request through socket in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn