PHP cURL 为特定端点添加“Access-Control-Allow-Origin: *”标头

Posted

技术标签:

【中文标题】PHP cURL 为特定端点添加“Access-Control-Allow-Origin: *”标头【英文标题】:PHP cURL add "Access-Control-Allow-Origin: *" header for specific endpoint 【发布时间】:2016-05-06 11:15:06 【问题描述】:

我的 php 服务器 (5.2) 端点 GET http://mydomain/get-code.php 上有这样的代码:

<?php
    header("Access-Control-Allow-Origin: *");

    $data = 'id=' . '123456' . '&' .
            'text=' . 'some text' . '&' .
            'code=' . urlencode($_GET['code']);
    $ch = curl_init('https://someapi.com/login/oauth');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    preg_match('/hash=([0-9a-f]+)/', $response, $out);
    echo $out[1];
    curl_close($ch);
?>

我正在从另一个域请求 GET http://mydomain/get-code.php。

我在浏览器控制台中收到 CORS 错误:

XMLHttpRequest cannot load http://mydomain/get-code.php No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9292' is therefore not allowed access.

有什么想法吗?

【问题讨论】:

这个header不应该来自服务器端吗? 您的问题是什么? cors 与客户无关。 enable-cors.org 我正在向另一个域请求 GET mydomain/get-code.php。 @AlonEitan 谢谢,我已经添加了 header("Access-Control-Allow-Origin: *"); 但这没有帮助 【参考方案1】:

Access-Control-Allow-Origin 用于接收请求的服务器,而不是发送请求的客户端。

【讨论】:

您需要将其添加到 mydomain/get-code.php 页面: header("Access-Control-Allow-Origin: *"); 你必须将它添加到被请求的页面(服务器),而不是从客户端(你使用 curl 的地方)

以上是关于PHP cURL 为特定端点添加“Access-Control-Allow-Origin: *”标头的主要内容,如果未能解决你的问题,请参考以下文章

PHP CURL“NSS:找不到客户端证书(未指定昵称)”问题

cURL PHP 在收到标头后挂起

linux下xampp集成环境中怎么为php添加curl扩展

Docker 中的 Kong : 在不使用 curl 的情况下配置 API 端点

如何在 PHP 中对谷歌地理编码 api 进行批量纬度/经度查找?

如何在 HTTP/1.1 中使用 PHP cURL