php实现api转接
实现API转接的基本方法
使用PHP实现API转接的核心是接收请求、转发请求并返回响应。以下是一个基本实现方案:
<?php
// 获取原始请求数据
$requestData = file_get_contents('php://input');
$headers = getallheaders();
// 设置目标API URL
$targetUrl = 'https://api.example.com/endpoint';
// 初始化cURL会话
$ch = curl_init($targetUrl);
// 设置cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
// 设置请求头
$forwardHeaders = [];
foreach ($headers as $key => $value) {
if (strtolower($key) !== 'host') {
$forwardHeaders[] = "$key: $value";
}
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $forwardHeaders);
// 执行请求并获取响应
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭cURL会话
curl_close($ch);
// 返回响应
http_response_code($httpCode);
echo $response;
?>
处理不同HTTP方法
需要考虑不同HTTP方法的处理方式:
// 根据请求方法设置不同的cURL选项
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
$queryString = http_build_query($_GET);
if ($queryString) {
$targetUrl .= '?' . $queryString;
}
break;
case 'POST':
curl_setopt($ch, CURLOPT_POST, true);
break;
case 'PUT':
case 'DELETE':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
break;
}
添加认证和安全措施
为确保安全性,可以添加认证和验证:
// 验证API密钥
$apiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
if ($apiKey !== 'YOUR_SECRET_KEY') {
http_response_code(401);
die('Unauthorized');
}
// 验证来源IP
$allowedIPs = ['192.168.1.1', '10.0.0.1'];
if (!in_array($_SERVER['REMOTE_ADDR'], $allowedIPs)) {
http_response_code(403);
die('Forbidden');
}
处理响应头
转发响应头以确保完整传递:
// 获取响应头并转发
$responseHeaders = [];
curl_setopt($ch, CURLOPT_HEADERFUNCTION,
function($curl, $header) use (&$responseHeaders) {
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) {
return $len;
}
$responseHeaders[strtolower(trim($header[0]))] = trim($header[1]);
return $len;
});
// 在输出响应前设置响应头
foreach ($responseHeaders as $name => $value) {
header("$name: $value");
}
错误处理和日志记录
添加错误处理和日志功能:
// 启用错误日志
curl_setopt($ch, CURLOPT_FAILONERROR, true);
// 记录请求和响应
file_put_contents('api_proxy.log',
date('Y-m-d H:i:s') . " - " .
$_SERVER['REQUEST_METHOD'] . " " .
$_SERVER['REQUEST_URI'] . "\n" .
"Response: $httpCode\n" .
"Body: " . substr($response, 0, 1000) . "\n\n",
FILE_APPEND);
// 处理cURL错误
if (curl_errno($ch)) {
http_response_code(500);
echo json_encode(['error' => curl_error($ch)]);
exit;
}
性能优化考虑
对于高性能需求,可以考虑以下优化:
// 启用HTTP持久连接
curl_setopt($ch, CURLOPT_TCP_KEEPALIVE, 1);
curl_setopt($ch, CURLOPT_TCP_KEEPIDLE, 120);
curl_setopt($ch, CURLOPT_TCP_KEEPINTVL, 60);
// 设置超时时间
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
// 启用GZIP压缩
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
完整的类实现
将功能封装成类便于重用:
class ApiProxy {
private $targetUrl;
private $allowedKeys = [];
public function __construct($targetUrl) {
$this->targetUrl = $targetUrl;
}
public function addAllowedKey($key) {
$this->allowedKeys[] = $key;
}
public function handleRequest() {
$this->validateRequest();
$response = $this->forwardRequest();
$this->sendResponse($response);
}
private function forwardRequest() {
$ch = curl_init($this->targetUrl . $this->getQueryString());
// 设置各种cURL选项...
return curl_exec($ch);
}
private function validateRequest() {
// 验证逻辑...
}
private function sendResponse($response) {
// 发送响应逻辑...
}
}
// 使用示例
$proxy = new ApiProxy('https://api.example.com');
$proxy->addAllowedKey('SECRET123');
$proxy->handleRequest();
这些方法提供了PHP实现API转接的完整方案,可以根据实际需求进行调整和扩展。







