使用PHP实现CORS 跨域资源共享,可传参origin通过限制,代码如下:

PHP代码
  1. <?php  
  2. /******** 定义Response返回header头格式及编码 ********/  
  3. header('Content-type: application/json; charset=utf-8');  
  4.   
  5. /******** 回调参数设置 ********/  
  6. $param="origin";  
  7. $origin_URL=$_REQUEST[$param];  
  8.   
  9.   
  10. /******** json_encode 转成=> encode_json *******/  
  11. function encode_json($str){  
  12.     return urldecode(json_encode(url_encode($str)));  
  13. }  
  14. function url_encode($str){  
  15.     if(is_array($str)){  
  16.         foreach($str as $key=>$value){  
  17.             $str[urlencode($key)]=url_encode($value);  
  18.         }  
  19.     }else{  
  20.         $str=urlencode($str);  
  21.     }  
  22.     return $str;  
  23. }  
  24.   
  25. /**************** \/\/反转义范例 ********************/  
  26. function stripslashes_deep($value){  
  27.     $value=is_array($value)?  
  28.                 array_map('stripslashes_deep',$value):  
  29.                 stripslashes($value);  
  30.     return $value;  
  31. }  
  32.   
  33. /******************** Example ******************************/  
  34. $array=array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));  
  35. $array=stripslashes_deep($array);  
  36.   
  37. /******************** Output *******************************/  
  38.   
  39. //echo encode_json(array('china'=>'钓鱼岛是中国的!','Japan'=>array('name'=>'日本狗!')));  
  40.   
  41.   
  42. /************ 定义Post过来什么数据就返回什么数据 ***********/  
  43. $res=array(  
  44.     'status'=>-1,
  45.     'name'=>isset($_POST['name'])?$_POST['name']:'',
  46.     'gender'=>isset($_POST['gender'])?$_POST['gender']:''
  47. );
  48. $arr=array(
  49.      "status"=>1,
  50.      "url"=>"http://www.liuxinxiu.com/",
  51.      "dataList"=>array(
  52.           "siteId"=>"1",
  53.           "title"=>urldecode('我的博客'),
  54.           "images"=>"http://192.168.9.100/upload/2015/06/20/moren.gif",
  55.           "indexNum"=>10,
  56.           "pageNum"=>"300",
  57.           "tagNum"=>"20",
  58.           "linkType"=>"linkTaobao",
  59.           "publishTime"=>"20:00:00"
  60.       )
  61. );
  62. $arr['dataList']['images']="http://www.liuxinxiu.com/upload/2015/06/20/moren.gif";
  63. //print_r($arr);
  64. /*************** 定义错误信息 ***************/
  65. $errStr='{"status":-1,"info":"Request Error"}';
  66. $errJson=json_decode($errStr,true); //json_decode转成了array数组
  67. //print_r($errJson) //转成了array数组
  68. /************** 获取客户端的Origin域名 **************/
  69. $origin=isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:'';
  70. /******** 定义符合规则的域名数组 ********/
  71. $allow_origin=array(
  72.     'http://liuxinxiu.com',  
  73.     'http://code.liuxinxiu.com',  
  74.     'http://test.liuxinxiu.com'  
  75. );  
  76.   
  77. /****************** 判断如果有POST过来数据 *********************/  
  78. if(isset($_POST['name'])&&isset($_POST['gender'])){
  79.     /********** 只要是POST请求过来无论合法与否都要正常通信 **********/
  80.      header('Access-Control-Allow-Methods:POST');
  81.      header('Access-Control-Allow-Headers:x-requested-with,content-type');
  82.     /******** 匹配客户端域名是否在数组列表中 ******/
  83.     if(in_array($origin,$allow_origin)){
  84.         header('Access-Control-Allow-Origin:'.$origin);
  85.         $res['status']=1;
  86.         $res['getUser']=$arr;
  87.         echo json_encode($res);
  88.     }
  89.     else if(!in_array($origin,$allow_origin)){
  90.         /******** 如有设置就取设置URL返回头信息 ********/
  91.         if(isset($origin_URL)){
  92.             header('Access-Control-Allow-Origin:'.$origin_URL);
  93.             $res['status']=1;
  94.             $res['getUser']=$arr;
  95.             echo encode_json($res);
  96.             //echo json_encode("中文", JSON_UNESCAPED_UNICODE);
  97.         }
  98.         /******** 如没有设置URL就返回错误信息  ********/
  99.         else{
  100.             header('Access-Control-Allow-Origin:'.$origin);
  101.             $errJson['status']=-1;
  102.             $errJson['info']="You don't have permission to submit!";  
  103.             echo encode_json($errJson);  
  104.         }  
  105.     }  
  106. }  
  107. /************ 没有所匹配的POST提交数据 ***********/  
  108. else{  
  109.     if($GLOBALS['HTTP_RAW_POST_DATA']){  
  110.             header('Access-Control-Allow-Origin:'.$origin);  
  111.             $errJson['status']=-1;  
  112.             $errJson['info']="Syntax error in parameters or arguments.";  
  113.             echo encode_json($errJson);  
  114.     }  
  115.     else{  
  116.         header("Content-type: text/html; charset=utf-8");  
  117.         echo 'It is forbidden for the URL request!';  
  118.     }  
  119. }  
  120. ?>  

PHP数据提交接口地址 (禁止使用GET访问):http://code.liuxinxiu.com/php/Interface/server.php

配合HTML代码如下:

XML/HTML代码
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8"/>  
  5.   
  6.     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>  
  8.     <meta name="format-detection"content="telephone=no">  
  9.     <meta name="apple-mobile-web-app-capable" content="yes" />  
  10.     <meta name="apple-mobile-web-app-status-bar-style" content="black" />  
  11.     <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>  
  12.     <title>跨域测试</title>  
  13. </head>  
  14. <body>  
  15. <h1 id="show"></h1>  
  16. <input type="button" value="Click me" onclick="msg()" />  
  17.   
  18. </body>  
  19. <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>  
  20. <script type='text/javascript'>  
  21. /********** 获取URL参数 **********/  
  22. function getQueryString(name){  
  23. var reg=new RegExp("(^|&)"+name+"=([^&]*)(&|$)","i");  
  24. var r=window.location.search.substr(1).match(reg);  
  25. if (r!=null) return unescape(r[2]); return null;  
  26. }  
  27.   
  28.   
  29. /********** 发起Ajax请求 **********/  
  30. function msg(){  
  31.     /******* 动态切换提交数据 *******/  
  32.     if(_origin){  
  33.         if(_name&&_gender){  
  34.             var data={name:_name,gender:_gender,origin:_origin};  
  35.         }  
  36.         else{  
  37.             var data={name:"xiaoming",gender:"male",origin:_origin};  
  38.         }  
  39.     }  
  40.     else if(_error==null){  
  41.         var data={name:"xiaoming",gender:"male"};  
  42.     }  
  43.     else if(_error){  
  44.         var data={xxx:111};  
  45.     }  
  46.     /******* 动态设置提交URL *******/  
  47.     if(_url){  
  48.         var urlPath=_url;  
  49.     }  
  50.     else{  
  51.         var urlPath='http://code.liuxinxiu.com/php/Interface/server.php';  
  52.     }  
  53.     $.ajax({  
  54.        type:'post',  
  55.        url:urlPath,  
  56.        data:data,  
  57.        cache:false,  
  58.        dataType:'json',  
  59.        success:function(data){  
  60.            if(data.name){  
  61.                 document.getElementById("show").innerHTML=data.name+' '+data.gender;  
  62.            }  
  63.            else if(data.status!=1){  
  64.                 document.getElementById("show").innerHTML=data.info;  
  65.            }  
  66.        },  
  67.        error:function(){  
  68.            console.log("请求错误//")  
  69.        }  
  70.     });  
  71. };  
  72.   
  73. /***********************************************************************************************  
  74. $.post("http://www.server.com/server.php",{name:"fdipzone",gender:"male"}).done(function(data){  
  75.     document.getElementById("show").innerHTML=data.name+' '+data.gender;  
  76. });  
  77. **********************************************************************************************/  
  78. </script>  
  79. </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

Tags: ,
PHP/Java | 评论(0) | 引用(0) | 阅读(3338)