首页 > 解决方案 > CORS 代理 (php) 无法连接到端口

问题描述

当我在浏览器地址栏中向http://fmgold.mvserver.be:4101/7.html发出请求时,我会正确接收元数据。

在我的应用程序中,由于 CORS 问题,对给定路径的请求失败。我无权访问服务器来修改标头,因此我正在尝试使用 PHP 创建 CORS 代理。

<?php
if( ! isset($curl_timeout))
    $curl_timeout = 30;

$headers = getallheaders();
$method = __('REQUEST_METHOD', $_SERVER);
$url = $_GET['url'];

// Check that we have a URL
if( ! $url)
    http_response_code(400) and exit("Url missing");

foreach($headers as $key => &$value) {
    $value = "$key: $value";
}

$curl = curl_init();
do
{
    curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_PORT => 4101,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_HEADER => TRUE,
            CURLOPT_TIMEOUT => $curl_timeout,
            CURLOPT_FOLLOWLOCATION => TRUE
        ]);
    // Method specific options
    switch($method)
    {
        case 'HEAD':
            curl_setopt($curl, CURLOPT_NOBODY, TRUE);
            break;
        case 'GET':
            break;
        case 'PUT':
        case 'POST':
        case 'DELETE':
        default:
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_POSTFIELDS, file_get_contents('php://input'));
            break;
    }
    // Perform request
    ob_start();
    curl_exec($curl) or http_response_code(500) and exit(curl_error($curl));
    $out = ob_get_clean();
    $url = curl_getinfo($curl, CURLINFO_REDIRECT_URL);
}

while($url and --$maxredirs > 0);

$info = curl_getinfo($curl);
curl_close($curl);

// Remove any existing headers
header_remove();

// Use gz, if acceptable
// ob_start('ob_gzhandler');

// Output headers
$header = substr($out, 0, $info['header_size']);
array_map('header', explode("\r\n", $header));

// And finally the body
echo substr($out, $info['header_size']);

// Helper function
function __($key, array $array, $default = null)
{
    return array_key_exists($key, $array) ? $array[$key] : $default;
}

我在实时服务器上运行 PHP,但是当我通过代理 php 调用 url 时(http://cors-proxy.myliveserver.com/proxy.php?url=http://fmgold.mvserver.be/7.html,我收到以下错误响应:

Failed to connect to fmgold.mvserver.be port 4101: Connection refused

将端口添加到 curl 请求似乎没有帮助。任何想法出了什么问题?

标签: phpproxycors

解决方案


三件事,

  1. 服务器端调用不受 Cross-Origin-Request 策略的约束,除非您在请求中添加“ Origin ”标头

  2. 您不需要在 curl 请求中设置端口。CURLOPT_PORT => 4101,这不是必需的

  3. 当您http://fmgold.mvserver.be:4101/7.html 从浏览器调用此 url 时,不涉及“ Origin ”标头,您可以通过向其发出GET请求来获得响应。

    但是在服务器端,当您发出请求时,您正在做的是获取服务器标头$headers = getallheaders();并将所有这些标头设置在您的 curl 请求中 CURLOPT_HTTPHEADER => $headers,并执行它。

    我的假设是$headers包含“ Origin ”标头,并且主机服务器因此拒绝您使用 CORS 的请求

    删除它CURLOPT_HTTPHEADER => $headers,并尝试。它应该工作


推荐阅读