使用说明
proxy.php?url=支持JSON/XML解析
<?php // 终极可靠版 proxy.php 带 CORS 支持和压缩处理 header('Content-Type: text/plain; charset=utf-8'); // 1. 设置 CORS 头 header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); header('Access-Control-Allow-Headers: *'); header('Cache-Control: no-store'); // 2. 获取原始未处理的整个查询字符串 $raw_query = $_SERVER['QUERY_STRING'] ?? ''; // 3. 直接提取url参数(不进行任何URL解码) if (preg_match('/url=(.*)/', $raw_query, $matches)) { $url_part = $matches[1]; // 获取url=后面的所有内容 // 4. 手动构建目标URL(保留所有原始字符) $targetUrl = $url_part; // 如果URL不以http://或https://开头,则添加https:// if (!preg_match('/^https?:\/\//i', $targetUrl)) { $targetUrl = 'https://' . $targetUrl; } $targetUrl = str_replace(' ', '%20', $targetUrl); // 只处理空格 // 5. 调试输出(实际使用时可以移除) error_log("RAW: $raw_query\nTARGET: $targetUrl\n\n", 3, 'proxy_debug.log'); // 6. 初始化 cURL $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $targetUrl, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_TIMEOUT => 10, CURLOPT_USERAGENT => 'Mozilla/5.0', CURLOPT_ENCODING => '', // 自动处理所有支持的编码类型 CURLOPT_HEADER => true, // 获取响应头 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, // 关键修改:强制降级到 HTTP/1.1 CURLOPT_HTTPHEADER => [ 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7', 'Upgrade-Insecure-Requests: 1' ] ]); // 7. 执行请求 $response = curl_exec($ch); if ($response === false) { header('Content-Type: text/plain; charset=utf-8'); die("请求失败,请检查:\n1. 目标URL是否可以公开访问\n2. 服务器网络连接\n3. 错误详情:" . curl_error($ch)); } // 8. 分离响应头和响应体 $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $headers = substr($response, 0, $header_size); $body = substr($response, $header_size); // 9. 处理内容编码 $content_encoding = ''; $content_type = 'text/plain; charset=utf-8'; foreach (explode("\r\n", $headers) as $header) { if (stripos($header, 'Content-Encoding:') === 0) { $content_encoding = trim(substr($header, 17)); } if (stripos($header, 'Content-Type:') === 0) { $content_type = trim(substr($header, 13)); } } // 10. 解压缩内容(如果需要) if ($content_encoding === 'gzip' && function_exists('gzdecode')) { $body = @gzdecode($body); if ($body === false) { $body = substr($response, $header_size); // 如果解压失败,使用原始内容 } } elseif ($content_encoding === 'deflate' && function_exists('gzuncompress')) { $body = @gzuncompress($body); if ($body === false) { $body = substr($response, $header_size); // 如果解压失败,使用原始内容 } } // 11. 设置正确的Content-Type header("Content-Type: $content_type"); // 12. 返回响应体 echo $body; // 关闭cURL资源 curl_close($ch); } else { header("HTTP/1.0 404 Not Found"); exit; } ?>
