<?php
// 創建一個代理服務器
$proxy = stream_socket_server('tcp://127.0.0.1:8000', $errno, $errstr);
if (!$proxy) {
die("創建代理服務器失敗:$errstr ($errno)");
}
while (true) {
// 接受客戶端連接請求
$client = stream_socket_accept($proxy);
if ($client) {
// 從客戶端讀取請求
$request = fread($client, 8192);
// 修改請求頭,偽裝為百度文心一言API的請求
$request = str_replace(
'Host: localhost:8000',
'Host: api.lovelive.tools',
$request
);
// 創建與API接口的連接
$api = stream_socket_client('tcp://api.lovelive.tools:80', $errno, $errstr, 30);
if ($api) {
// 向API接口發送請求
fwrite($api, $request);
// 獲取API的響應並返回給客戶端
while (!feof($api)) {
fwrite($client, fread($api, 8192));
}
fclose($api);
} else {
fclose($client);
}
}
}
fclose($proxy);
將代碼保存為proxy.php,通過命令行運行:
php proxy.php
此時代理服務器運行在127.0.0.1:8000端口。
使用curl命令通過代理髮送請求示例:
curl -x localhost:8000 https://api.lovelive.tools/api/SweetNothings/1
server {
listen 80;
server_name api.mydomain.com;
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host api.lovelive.tools;
}
}
反向代理PHP代碼示例,實現請求轉發與響應返回:
<?php
// 創建與API接口的連接
$api = stream_socket_client('tcp://api.lovelive.tools:80', $errno, $errstr, 30);
if ($api) {
// 從客戶端讀取請求体
$request = file_get_contents('php://input');
// 向API接口發送請求
fwrite($api, $request);
// 獲取API響應並返回客戶端
while (!feof($api)) {
echo fread($api, 8192);
}
fclose($api);
} else {
header('HTTP/1.1 500 Internal Server Error');
echo "與API接口連接失敗";
}
將代碼保存為reverse_proxy.php,命令行啟動:
php -S localhost:8000 reverse_proxy.php
反向代理服務器即可在localhost:8000端口運行。
客戶端請求直接發送至api.mydomain.com,服務器負責轉發至百度文心一言API並返迴響應。
相關標籤:
API