【问题标题】:Call a PHP from another PHP (without cURL)从另一个 PHP 调用一个 PHP(没有 cURL)
【发布时间】:2015-05-13 15:32:48
【问题描述】:

我有一个必须在另一个域上调用 PHP 的 HTML 页面。大多数浏览器的“同源规则”禁止该调用。所以我想在我的域上调用一个 PHP 来调用目标域上的一个 PHP。我想避免使用 cURL,所以我决定在使用 $context 的传递 PHP 中使用 fopen

$params = array('http' => array('method'=>'POST',
                                'header'=>'Content-type: application/json',
                                'content'=>json_encode($_POST)));
$ctx = stream_context_create($params);
$fp = fopen('https://other_domain.com/test.php', 'rb', false, $ctx);
$response = stream_get_contents($fp);
echo $response;

但是 test.php 中传入的$_POST 似乎是空的。有任何想法吗?

【问题讨论】:

    标签: php json curl fopen


    【解决方案1】:

    尝试使用 http_build_query() 构建参数

    $postdata = http_build_query(
        array(
            'json' => json_encode($_POST),
        )
    );
    

    然后

    $params = array('http' => array('method'=>'POST',
                                'header'=>'Content-type: application/x-www-form-urlencoded',
                                'content'=> $postdata));
    

    在另一个网站上通过$_POST['json']获取它

    【讨论】:

      【解决方案2】:

      除非您的服务器支持将 application/json 作为 POST 内容类型,否则您的代码将无法正常工作:HTTP 服务器期望 POST 数据始终是 application/x-www-form-encodedmultipart/form-data 之一。您需要重写您的代码,以便以一种受支持的类型发送 POST 数据。

      【讨论】:

      • 不确定你有没有直接的事实 Fred
      • @DavidBarker 正如我所说,除非您有支持application/json的服务器,因为普通的 HTTP 服务器通常只支持两种“标准”表单数据类型。例如,参见Form content type for a json HTTP POST? 的 cmets 我不知道目前有任何 HTTP 服务器支持 application/json 作为内容类型开箱即用
      • 服务器不是问题,如果您从 HTML 表单发送,您所说的是正确的。 PHP 流非常不同。
      • @DavidBarker 是的 - 一个不同的问题空间。
      【解决方案3】:

      我是这样管理的:

      $postData = file_get_contents('php://input');
      $params = array('http' => array('method'=>'POST',
                                      'header'=>'Content-type: application/x-www-form-urlencoded',
                                      'content'=>$postData));
      $ctx = stream_context_create($params);
      $url = 'https://other_domain.com/test.php';
      $fp = fopen($url, 'rb', false, $ctx);
      $response = stream_get_contents($fp);
      echo $response;
      

      这很容易处理所有传入的 POST 数据并转发任何响应。感谢您的所有帖子!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多