<?php // Create a proxy server $proxy = stream_socket_server('tcp://127.0.0.1:8000', $errno, $errstr); if (!$proxy) { die("Failed to create proxy server: $errstr ($errno)"); } while (true) { // Accept client connection $client = stream_socket_accept($proxy); if ($client) { // Read request from client $request = fread($client, 8192); // Modify request header to mimic Baidu Wenxin Yiyan API request $request = str_replace( 'Host: localhost:8000', 'Host: api.lovelive.tools', $request ); // Connect to API server $api = stream_socket_client('tcp://api.lovelive.tools:80', $errno, $errstr, 30); if ($api) { // Send request to API fwrite($api, $request); // Relay API response back to client while (!feof($api)) { fwrite($client, fread($api, 8192)); } fclose($api); } else { fclose($client); } } } fclose($proxy);
Save the code as proxy.php and run from the command line:
php proxy.php
The proxy server will now run on 127.0.0.1:8000.
Example of sending a request through the proxy using 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; } }
Sample PHP code for reverse proxy to forward requests and return responses:
<?php // Connect to API server $api = stream_socket_client('tcp://api.lovelive.tools:80', $errno, $errstr, 30); if ($api) { // Read request body from client $request = file_get_contents('php://input'); // Send request to API fwrite($api, $request); // Relay API response back to client while (!feof($api)) { echo fread($api, 8192); } fclose($api); } else { header('HTTP/1.1 500 Internal Server Error'); echo "Failed to connect to API server"; }
Save this as reverse_proxy.php and run:
php -S localhost:8000 reverse_proxy.php
The reverse proxy server will now run on localhost:8000.
Clients send requests directly to api.mydomain.com, and the server forwards them to Baidu Wenxin Yiyan API and returns the responses.