PHP HTTP 请求

作者:IT技术圈子 阅读:2 日期:2025年09月10日

# PHP HTTP 请求

PHP 提供了多种方式来发送 HTTP 请求,以下是常用的方法:

## 1. cURL (推荐)

cURL 是 PHP 中最强大和灵活的 HTTP 客户端。

```php // 初始化 cURL $ch = curl_init();

// 设置请求选项 curl_setopt($ch, CURLOPT_URL, "https://example.com/api"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应而不是直接输出 curl_setopt($ch, CURLOPT_HEADER, false); // 不包含响应头 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 跟随重定向

// 对于 POST 请求 curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['key' => 'value']));

// 执行请求 $response = curl_exec($ch);

// 检查错误 if (curl_errno($ch)) { echo 'cURL 错误: ' . curl_error($ch); }

// 获取 HTTP 状态码 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// 关闭 cURL 资源 curl_close($ch);

// 处理响应 echo $response; ```

## 2. file_get_contents()

对于简单的 GET 请求,可以使用 `file_get_contents()`:

```php $response = file_get_contents('https://example.com/api'); if ($response === false) { echo "请求失败"; } else { echo $response; } ```

使用流上下文添加更多选项:

```php $options = [ 'http' => [ 'method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'content' => http_build_query(['key' => 'value']) ] ];

$context = stream_context_create($options); $response = file_get_contents('https://example.com/api', false, $context); ```

## 3. Guzzle HTTP 客户端 (第三方库)

Guzzle 是 PHP 最流行的 HTTP 客户端库。

安装: ```bash composer require guzzlehttp/guzzle ```

使用: ```php require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();

// GET 请求 $response = $client->get('https://example.com/api'); echo $response->getBody();

// POST 请求 $response = $client->post('https://example.com/api', [ 'form_params' => [ 'key' => 'value' ] ]); ```

## 4. fopen() 包装器

PHP 的流包装器也可以用于 HTTP 请求:

```php $handle = fopen('https://example.com/api', 'r'); if ($handle) { $response = stream_get_contents($handle); fclose($handle); echo $response; } else { echo "请求失败"; } ```

## 5. HTTP 扩展 (pecl_http)

这是一个较少使用的扩展,但提供了高级功能:

```php $request = new HttpRequest('https://example.com/api', HttpRequest::METH_GET); $request->send(); echo $request->getResponseBody(); ```

## 最佳实践

1. 始终验证 SSL 证书(在生产环境中) 2. 设置合理的超时时间 3. 处理错误和异常 4. 考虑使用 try-catch 块 5. 对于复杂应用,推荐使用 Guzzle

## 示例:完整的 cURL 函数

```php function sendHttpRequest($url, $method = 'GET', $data = [], $headers = []) { $ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_TIMEOUT, 30);

// 设置方法 if ($method === 'POST') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } elseif ($method === 'PUT' || $method === 'DELETE') { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); }

// 设置头部 if (!empty($headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); }

$response = curl_exec($ch); $error = curl_error($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

return [ 'status' => $httpCode, 'body' => $response, 'error' => $error ]; }

// 使用示例 $result = sendHttpRequest( 'https://example.com/api', 'POST', ['key' => 'value'], ['Content-Type: application/json'] ); ```

选择哪种方法取决于你的具体需求、PHP 版本和项目复杂性。对于现代 PHP 应用,Guzzle 通常是首选。

  END