如何提出PH​​P CORS请求? [英] How do I make a PHP CORS request?

查看:77
本文介绍了如何提出PH​​P CORS请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP Curl向我们的API站点发出请求.目前,我正在尝试提出一个简单的请求

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

API站点有一个目录,该目录返回JSON格式的数据.脚本如下所示:\

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;
?>

如果我从浏览器访问API站点(api/test_json),则会看到json数据:

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

我在另一个域上有一个PHP脚本试图获取JSON数据:

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);
?>

但是当我跑步时,我得到了bool(false)的返回.我有错过任何密码吗?

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

推荐答案

服务器端调用不受跨域请求"策略的约束.问题出在API的可用性方面.是否需要任何认证?可能是当您从浏览器请求它时,您有一个会话cookie.

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.

仅将代码简化为 file_get_contents("http://ourapi.com/test_json/"); 启用所有错误显示,并查看是否给出任何错误.

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

这篇关于如何提出PH​​P CORS请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆