How do I make a PHP CORS request?

邮差的信 提交于 2021-01-27 17:49:11

问题


I'm trying to use PHP Curl to make a request to our API site. At the moment, I'm trying to make a simple request

The API site has a directory which returns JSON formatted data. The script is shown below:\

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

$arr['id'] = '001';
$arr['desc'] = 'Simple JSON output';

$json = json_encode($arr);

echo $json;
?>

If I access the API site (api/test_json) from my browser, I see the json data:

I have a PHP script on another domain trying to get the JSON data:

<?php
$url = "http://ourapi.com/test_json/";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
$str = curl_exec($curl);
curl_close($curl);

var_dump($str);
?>

But as I run, I get a return of bool(false). Did I miss anything on my codes?


回答1:


Server-side calls are not subject of Cross-Origin-Request policy. The problem is somewhere in availability of the API. Is there any authenticaion required? Probably when you request it from browser you have a session cookie.

Simplify you code just to file_get_contents("http://ourapi.com/test_json/"); enable all errors display and see is it gives any errors.



来源:https://stackoverflow.com/questions/40150073/how-do-i-make-a-php-cors-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!