PHP 发起 HTTP 请求有以下几种方式:cURL:功能强大,提供高级 HTTP 控制。fopen() 和 fsockopen():低级函数,提供基本 HTTP 功能。stream_context_create():可创建自定义 HTTP 请求头和 cookie 的流上下文。HTTPful:第三方库,封装 cURL 并简化操作。

PHP 发起 HTTP 请求的方式
PHP 提供了多种方法来发起 HTTP 请求,包括:
1. cURL
cURL 是一个功能强大的库,可用于执行各种 HTTP 操作。它提供对 HTTP 头部、身份验证和 cookie 的高级控制。
立即学习“PHP免费学习笔记(深入)”;
<code class="php"><?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://example.com"); $result = curl_exec($ch); curl_close($ch);</code>
2. fopen() 和 fsockopen()
fopen() 和 fsockopen() 是 PHP 的低级函数,可用于打开和操作套接字连接。它们提供基本的 HTTP 功能,但缺乏 cURL 的高级控制。
<code class="php"><?php
$fp = fsockopen("example.com", 80);
fwrite($fp, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
while (!feof($fp)) {
echo fgets($fp);
}
fclose($fp);</code>3. stream_context_create()
stream_context_create() 函数可用于创建具有自定义选项的流上下文,包括 HTTP 请求头和 cookie。
<code class="php"><?php
$context = stream_context_create([
'http' => [
'header' => "Content-Type: application/json",
'method' => 'POST',
'content' => json_encode(['name' => 'John'])
]
]);
$result = file_get_contents("http://example.com", false, $context);</code>4. HTTPful
HTTPful 是一个第三方库,它封装了 cURL 并提供了更简单的界面。它提供对常见 HTTP 操作的简化方法。
<code class="php"><?php
require 'vendor/autoload.php';
use Httpful\Request;
$response = Request::get('http://example.com')->send();</code>以上就是php 哪些方式http请求的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号