在PHP中,发送HTTP请求通常使用cURL
库或file_get_contents()
函数。以下是两种常见的请求写法:
cURL是一个功能强大的库,支持多种协议(如HTTP、HTTPS、FTP等),并且可以设置各种请求参数。
<?php
// 初始化cURL会话
$ch = curl_init();
// 设置请求的URL
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/resource?param1=value1¶m2=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;
?>
<?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;
?>
file_get_contents()
发送HTTP请求file_get_contents()
函数也可以用于发送简单的HTTP请求,通常用于GET请求。
<?php
// 设置请求的URL
$url = "https://example.com/api/resource?param1=value1¶m2=value2";
// 使用file_get_contents发送GET请求
$response = file_get_contents($url);
// 输出响应
echo $response;
?>
<?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;
?>
Guzzle是一个流行的PHP HTTP客户端,提供了更简洁的API来发送HTTP请求。
composer require guzzlehttp/guzzle
<?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();
?>
<?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();
?>
根据你的需求选择合适的工具来发送HTTP请求。