php实现api转接
PHP实现API转接的方法
使用PHP实现API转接(即作为中间层转发客户端请求到目标API)可以通过多种方式完成。以下是几种常见实现方案:
cURL方式实现
<?php
$targetUrl = 'https://api.example.com/endpoint';
$ch = curl_init($targetUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
// 转发原始请求头(可选)
$headers = [];
foreach (getallheaders() as $name => $value) {
$headers[] = "$name: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 转发原始请求方法
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
// 转发请求体(POST/PUT等情况)
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
$input = file_get_contents('php://input');
curl_setopt($ch, CURLOPT_POSTFIELDS, $input);
}
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// 返回响应
http_response_code($statusCode);
echo $response;
?>
Guzzle HTTP客户端实现
需要先安装Guzzle:
composer require guzzlehttp/guzzle
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$targetUrl = 'https://api.example.com/endpoint';
try {
$response = $client->request(
$_SERVER['REQUEST_METHOD'],
$targetUrl,
[
'headers' => getallheaders(),
'body' => file_get_contents('php://input')
]
);
http_response_code($response->getStatusCode());
echo $response->getBody();
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
?>
处理认证和安全性
在转发API请求时需要考虑安全措施:
// 验证来源IP(可选)
$allowedIps = ['192.168.1.0/24'];
if (!in_array($_SERVER['REMOTE_ADDR'], $allowedIps)) {
http_response_code(403);
exit;
}
// 添加API密钥验证
if ($_SERVER['HTTP_API_KEY'] !== 'your-secret-key') {
http_response_code(401);
exit;
}
缓存响应优化性能
$cacheKey = md5($_SERVER['REQUEST_URI'] . file_get_contents('php://input'));
$cacheFile = "cache/$cacheKey.json";
if (file_exists($cacheFile) && time() - filemtime($cacheFile) < 3600) {
$cached = json_decode(file_get_contents($cacheFile));
http_response_code($cached->status);
echo $cached->body;
exit;
}
// ...执行API请求后保存到缓存
file_put_contents($cacheFile, json_encode([
'status' => $statusCode,
'body' => $response
]));
日志记录
$logData = [
'date' => date('Y-m-d H:i:s'),
'method' => $_SERVER['REQUEST_METHOD'],
'uri' => $_SERVER['REQUEST_URI'],
'ip' => $_SERVER['REMOTE_ADDR'],
'status' => $statusCode
];
file_put_contents(
'logs/api_proxy.log',
json_encode($logData) . PHP_EOL,
FILE_APPEND
);
这些方法可以根据实际需求组合使用,构建完整的API转接服务。需要注意处理跨域请求(CORS)、错误处理和性能优化等问题。







