PHP 发送 HTTP 请求方式

PHP 中我们发送 http 请求常用的是 curl,今天接触到其他几种方式,这里做下简单的记录。

curl 方式

这种是最常用的方式,我这里就不做记录了,平时开发中用的最多了。

stream 流的方式

我们可以使用 file_get_contents 的第三个参数来传递一个包装的 http stream,下面来个简单的代码:

1
2
3
4
5
6
7
8
9
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
)
);
$context = stream_context_create($opts);
$result = file_get_contents("http://www.baidu.com", false, $context);
var_dump($result);

详细信息请阅读官方文档

socket方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
参数说明:
hostname: 主机名
port: 端口
errNo: 错误码
errMsg: 错误信息
timeout: 设置连接的时限,单位为秒
*/
$fp = fsockopen("www.baidu.com", 80, $errNo, $errMsg, 10);
if (!$fp) {
echo $errNo, "<br />", $errMsg;
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.baidu.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}

上面只是一个简单的例子,具体用法详细参考官方文档

©版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 & 作者信息

Happy Coding

坚持原创技术分享,您的支持将鼓励我继续创作!
Flyertutor WeChat Pay

WeChat Pay

Flyertutor Alipay

Alipay