使用PHP实现CORS 跨域资源共享,可传参origin通过限制,代码如下:
PHP代码
- <?php
- /******** 定义Response返回header头格式及编码 ********/
- header('Content-type: application/json; charset=utf-8');
- /******** 回调参数设置 ********/
- $param="origin";
- $origin_URL=$_REQUEST[$param];
- /******** json_encode 转成=> encode_json *******/
- function encode_json($str){
- return urldecode(json_encode(url_encode($str)));
- }
- function url_encode($str){
- if(is_array($str)){
- foreach($str as $key=>$value){
- $str[urlencode($key)]=url_encode($value);
- }
- }else{
- $str=urlencode($str);
- }
- return $str;
- }
- /**************** \/\/反转义范例 ********************/
- function stripslashes_deep($value){
- $value=is_array($value)?
- array_map('stripslashes_deep',$value):
- stripslashes($value);
- return $value;
- }
- /******************** Example ******************************/
- $array=array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
- $array=stripslashes_deep($array);
- /******************** Output *******************************/
- //echo encode_json(array('china'=>'钓鱼岛是中国的!','Japan'=>array('name'=>'日本狗!')));
- /************ 定义Post过来什么数据就返回什么数据 ***********/
- $res=array(
- 'status'=>-1,
- 'name'=>isset($_POST['name'])?$_POST['name']:'',
- 'gender'=>isset($_POST['gender'])?$_POST['gender']:''
- );
- $arr=array(
- "status"=>1,
- "url"=>"http://www.liuxinxiu.com/",
- "dataList"=>array(
- "siteId"=>"1",
- "title"=>urldecode('我的博客'),
- "images"=>"http://192.168.9.100/upload/2015/06/20/moren.gif",
- "indexNum"=>10,
- "pageNum"=>"300",
- "tagNum"=>"20",
- "linkType"=>"linkTaobao",
- "publishTime"=>"20:00:00"
- )
- );
- $arr['dataList']['images']="http://www.liuxinxiu.com/upload/2015/06/20/moren.gif";
- //print_r($arr);
- /*************** 定义错误信息 ***************/
- $errStr='{"status":-1,"info":"Request Error"}';
- $errJson=json_decode($errStr,true); //json_decode转成了array数组
- //print_r($errJson) //转成了array数组
- /************** 获取客户端的Origin域名 **************/
- $origin=isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:'';
- /******** 定义符合规则的域名数组 ********/
- $allow_origin=array(
- 'http://liuxinxiu.com',
- 'http://code.liuxinxiu.com',
- 'http://test.liuxinxiu.com'
- );
- /****************** 判断如果有POST过来数据 *********************/
- if(isset($_POST['name'])&&isset($_POST['gender'])){
- /********** 只要是POST请求过来无论合法与否都要正常通信 **********/
- header('Access-Control-Allow-Methods:POST');
- header('Access-Control-Allow-Headers:x-requested-with,content-type');
- /******** 匹配客户端域名是否在数组列表中 ******/
- if(in_array($origin,$allow_origin)){
- header('Access-Control-Allow-Origin:'.$origin);
- $res['status']=1;
- $res['getUser']=$arr;
- echo json_encode($res);
- }
- else if(!in_array($origin,$allow_origin)){
- /******** 如有设置就取设置URL返回头信息 ********/
- if(isset($origin_URL)){
- header('Access-Control-Allow-Origin:'.$origin_URL);
- $res['status']=1;
- $res['getUser']=$arr;
- echo encode_json($res);
- //echo json_encode("中文", JSON_UNESCAPED_UNICODE);
- }
- /******** 如没有设置URL就返回错误信息 ********/
- else{
- header('Access-Control-Allow-Origin:'.$origin);
- $errJson['status']=-1;
- $errJson['info']="You don't have permission to submit!";
- echo encode_json($errJson);
- }
- }
- }
- /************ 没有所匹配的POST提交数据 ***********/
- else{
- if($GLOBALS['HTTP_RAW_POST_DATA']){
- header('Access-Control-Allow-Origin:'.$origin);
- $errJson['status']=-1;
- $errJson['info']="Syntax error in parameters or arguments.";
- echo encode_json($errJson);
- }
- else{
- header("Content-type: text/html; charset=utf-8");
- echo 'It is forbidden for the URL request!';
- }
- }
- ?>
PHP数据提交接口地址 (禁止使用GET访问):http://code.liuxinxiu.com/php/Interface/server.php
配合HTML代码如下:
XML/HTML代码
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8"/>
- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
- <meta name="format-detection"content="telephone=no">
- <meta name="apple-mobile-web-app-capable" content="yes" />
- <meta name="apple-mobile-web-app-status-bar-style" content="black" />
- <style>body,html {background:#fff;font-family: "Lucida Grande",Calibri,Arial;font-size:12pt;color: #333;background: #f8f8f8;text-align:center;}*{margin:0;padding:0;}h1{line-height:1.6em;font-size:24px;text-indent:.5em;padding-top:.6em}i{line-height:2em;font-size:18px;color:#999;}.line{height:10px;border-bottom:1px solid #ccc;font-size:0;overflow:hidden;}</style>
- <title>跨域测试</title>
- </head>
- <body>
- <h1 id="show"></h1>
- <input type="button" value="Click me" onclick="msg()" />
- </body>
- <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
- <script type='text/javascript'>
- /********** 获取URL参数 **********/
- function getQueryString(name){
- var reg=new RegExp("(^|&)"+name+"=([^&]*)(&|$)","i");
- var r=window.location.search.substr(1).match(reg);
- if (r!=null) return unescape(r[2]); return null;
- }
- /********** 发起Ajax请求 **********/
- function msg(){
- /******* 动态切换提交数据 *******/
- if(_origin){
- if(_name&&_gender){
- var data={name:_name,gender:_gender,origin:_origin};
- }
- else{
- var data={name:"xiaoming",gender:"male",origin:_origin};
- }
- }
- else if(_error==null){
- var data={name:"xiaoming",gender:"male"};
- }
- else if(_error){
- var data={xxx:111};
- }
- /******* 动态设置提交URL *******/
- if(_url){
- var urlPath=_url;
- }
- else{
- var urlPath='http://code.liuxinxiu.com/php/Interface/server.php';
- }
- $.ajax({
- type:'post',
- url:urlPath,
- data:data,
- cache:false,
- dataType:'json',
- success:function(data){
- if(data.name){
- document.getElementById("show").innerHTML=data.name+' '+data.gender;
- }
- else if(data.status!=1){
- document.getElementById("show").innerHTML=data.info;
- }
- },
- error:function(){
- console.log("请求错误//")
- }
- });
- };
- /***********************************************************************************************
- $.post("http://www.server.com/server.php",{name:"fdipzone",gender:"male"}).done(function(data){
- document.getElementById("show").innerHTML=data.name+' '+data.gender;
- });
- **********************************************************************************************/
- </script>
- </html>
HTML访问地址 (测试跨域) ==> http://test1.liuxinxiu.com/php/Interface/html/server.html?n=php
HTML访问地址 (非法参数) ==> http://test1.liuxinxiu.com/php/Interface/html/server.html?error=php