How to send HTTP request through socket in PHP

墨辰丷
Release: 2023-03-29 18:46:01
Original
1623 people have browsed it

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 = <<
        
Copy after login

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); }
Copy after login

##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);
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!