插件窝 干货文章 php请求报文 请求写法

php请求报文 请求写法

请求 cURL 设置 response 458    来源:    2025-03-19

在PHP中,发送HTTP请求通常使用cURL库或file_get_contents()函数。以下是两种常见的请求写法:

1. 使用cURL发送HTTP请求

cURL是一个功能强大的库,支持多种协议(如HTTP、HTTPS、FTP等),并且可以设置各种请求参数。

GET请求示例:

<?php
// 初始化cURL会话
$ch = curl_init();

// 设置请求的URL
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/resource?param1=value1&param2=value2");

// 设置请求方法为GET(默认就是GET,可以不设置)
curl_setopt($ch, CURLOPT_HTTPGET, true);

// 设置返回结果为字符串而不是直接输出
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 执行请求并获取响应
$response = curl_exec($ch);

// 检查是否有错误发生
if (curl_errno($ch)) {
    echo 'cURL Error: ' . curl_error($ch);
}

// 关闭cURL会话
curl_close($ch);

// 输出响应
echo $response;
?>

POST请求示例:

<?php
// 初始化cURL会话
$ch = curl_init();

// 设置请求的URL
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/resource");

// 设置请求方法为POST
curl_setopt($ch, CURLOPT_POST, true);

// 设置POST数据
$postData = [
    'param1' => 'value1',
    'param2' => 'value2',
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

// 设置返回结果为字符串而不是直接输出
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 执行请求并获取响应
$response = curl_exec($ch);

// 检查是否有错误发生
if (curl_errno($ch)) {
    echo 'cURL Error: ' . curl_error($ch);
}

// 关闭cURL会话
curl_close($ch);

// 输出响应
echo $response;
?>

2. 使用file_get_contents()发送HTTP请求

file_get_contents()函数也可以用于发送简单的HTTP请求,通常用于GET请求。

GET请求示例:

<?php
// 设置请求的URL
$url = "https://example.com/api/resource?param1=value1&param2=value2";

// 使用file_get_contents发送GET请求
$response = file_get_contents($url);

// 输出响应
echo $response;
?>

POST请求示例:

<?php
// 设置请求的URL
$url = "https://example.com/api/resource";

// 设置POST数据
$postData = http_build_query([
    'param1' => 'value1',
    'param2' => 'value2',
]);

// 设置请求上下文选项
$options = [
    'http' => [
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postData,
    ],
];

// 创建上下文
$context = stream_context_create($options);

// 使用file_get_contents发送POST请求
$response = file_get_contents($url, false, $context);

// 输出响应
echo $response;
?>

3. 使用Guzzle库发送HTTP请求

Guzzle是一个流行的PHP HTTP客户端,提供了更简洁的API来发送HTTP请求。

安装Guzzle:

composer require guzzlehttp/guzzle

GET请求示例:

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();

$response = $client->request('GET', 'https://example.com/api/resource', [
    'query' => [
        'param1' => 'value1',
        'param2' => 'value2',
    ],
]);

echo $response->getBody();
?>

POST请求示例:

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();

$response = $client->request('POST', 'https://example.com/api/resource', [
    'form_params' => [
        'param1' => 'value1',
        'param2' => 'value2',
    ],
]);

echo $response->getBody();
?>

总结

  • cURL:功能强大,适合复杂的请求场景。
  • file_get_contents:简单易用,适合简单的GET请求。
  • Guzzle:现代HTTP客户端,提供了更简洁的API,适合复杂的HTTP请求场景。

根据你的需求选择合适的工具来发送HTTP请求。