iis服务器配置php代理解决跨域

配置

首先需要配置iis环境,网上有很多教程,这里不再赘述了。我们直接开始配置php代理。

  1. 检查iis环境有没有支持CGI。

    打开 控制面板->程序->打开或关闭windows功能->Internet信息服务->万维网服务->应用程序开发功能。如果CGI没有勾选,需要勾选它。

  2. php官网下载php 5.x,解压到d:\php目录。
  3. 在d:\php目录下找到php.ini-development文件,把它复制到桌面,然后用编辑器打开它。
  4. 找到;extension=php_curl.dll把前面的;号删除。
  5. 找到; extension_dir = "ext"把前面的;号删除。然后把"ext"改成"d:\php\ext"
  6. 将修改后的php.ini-development重命名为php.ini,然后移动到c:\windows根目录下。
  7. 添加php模块映射

    打开 控制面板->系统和安全->管理工具->Internet 信息服务(IIS)管理器->处理程序映射->添加模块映射。

    • 请求路径:*.php
    • 模块:FastCgiModule
    • 可执行文件(可选):d:\php\php-cgi.exe
    • 名称:php

以上iis的php代理配置就完成了。

需要注意一点:php代理配置完毕之后,如果再次修改php.ini然后移动到c:\windows根目录下,需要重启电脑,修改后的php.ini才能生效。

使用

  1. 将下面的php文件放到项目里面。

    <?php
    /**relay.php*/
    class interface_relay
    {
          
          
        /**接口根地址(此处是需要修改的地方)*/ 
        const URL_ROOT = '';
    
        /**字符集*/
        const CHARSET = 'UTF-8'; 
        /**GET*/ 
        private $msGets = ''; 
        /**POST*/ 
        private $maGetPostData = array();
        /*true为POST请求*/
        private $isPost = true;
        /*保存请求api的url*/
        private $apiUrl = '';
    
        private $postHeader = array();
    
        function __construct(){
          
          
    
            if ($_SERVER['REQUEST_METHOD'] == 'POST'){
          
          
                 $this->isPost = true;
                 $this->getGET();
                 $this->getPOST();
                 $sUrl = self::URL_ROOT .$this->apiUrl;
            }else{
          
          
                 $this->isPost =false;
                 $this->getGET();
                 $sUrl = self::URL_ROOT .$this->apiUrl.'?'. $this->msGets;
            }
            $headers = getallheaders();
            if (array_key_exists('Authorization', $headers)) {
          
          
                $this->postHeader[] = 'Authorization:'.$headers['Authorization'];
            }
            //$this->postHeader[] = 'Content-Type:image/jpg';
            if(!empty($headers['Code'])){
          
          
                $this->postHeader[] = 'Code:'.$headers['Code'];
            }
            if(array_key_exists('Latitude', $headers)){
          
          
                $this->postHeader[] = 'latitude:'.$headers['Latitude'];
            }
            if(array_key_exists('Longitude', $headers)){
          
          
                $this->postHeader[] = 'longitude:'.$headers['Longitude'];
            }
    
            if (isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP']){
          
          
                $this->postHeader[] = 'CLIENT_IP:'.$_SERVER['HTTP_CLIENT_IP'];
            }
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']){
          
          
                $this->postHeader[] = 'X_FORWARDED_FOR:'.$_SERVER['HTTP_X_FORWARDED_FOR'];
            }
            if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR']){
          
          
                $this->postHeader[] = 'REMOTE_ADDR:'.$_SERVER['REMOTE_ADDR'];
            }
    
            echo $this->getContent($sUrl);
        } 
     
        function __destruct() {
          
          
            unset($maGetPostData, $msGets); 
        } 
     
        /**
         * 载入POST数据
         * @return bool
         * */ 
        private function getPOST() {
          
          
            $this->maGetPostData[] = @file_get_contents('php://input');
            return count($this->maGetPostData) >= 1;
        } 
     
        /**
         * 载入GET数据
         * @return bool
         * */ 
        private function getGET() {
          
          
            /*取得GET内容*/ 
            if (count($_GET) > 0) {
          
          
                $aTmp = array(); 
                foreach ($_GET as $sKey => $sVal){
          
          
                    if($sKey == 'url'){
          
          
                        $this->apiUrl = $sVal;
                    }else {
          
          
                        $aTmp[] = $sKey .'='. urlencode($sVal);
                    }
                }
                $this->msGets = implode('&', $aTmp); 
                return true; 
            } 
            else {
          
          
                return false;
            }
        } 
     
        /**
         * 读取远程接口返回的内容
         * @return string
         * */ 
        private function getContent($sGetUrl) {
          
          
    
            $ch = curl_init();
            curl_setopt ($ch, CURLOPT_URL, $sGetUrl); //设置GET的URL地址
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);//将结果保存成字符串
            curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 120);//连接超时时间s
            curl_setopt ($ch, CURLOPT_TIMEOUT, 120);//执行超时时间s
            curl_setopt ($ch, CURLOPT_DNS_CACHE_TIMEOUT, 1800);//DNS解析缓存保存时间半小时
            curl_setopt ($ch, CURLOPT_HEADER, 0);//丢掉头信息
            curl_setopt ($ch, CURLOPT_HTTPHEADER, $this->postHeader);
            //curl_setopt ($ch, CURLOPT_FAILONERROR, true);
            //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
    
            if ($this->isPost){
          
          
                //存在POST数据需要提交
                curl_setopt($ch, CURLOPT_POST, 1); //启用POST数据
                curl_setopt($ch, CURLOPT_POSTFIELDS, implode('', $this->maGetPostData));//提交POST数据 
            }
            $file = curl_exec($ch);
            $info = curl_getinfo($ch);
            header('Content-Type: ' . $info['content_type']);
            //header('Content-Length:' . $info['download_content_length']);
            $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
            http_response_code($info['http_code']);
            curl_close($ch);
            unset($ch);
    
            return $file;
        }
    
         private function getallheaders(){
          
          
            foreach ($_SERVER as $name => $value){
          
          
                if (substr($name, 0, 5) == 'HTTP_'){
          
          
                    $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
                }
            }
            return $headers;
         }
    } 
     
    $o = new interface_relay();
    unset($o);
    ?>
    
  2. 跨域请求的时候,请求这个php文件并使用url拼接api地址。

    示例:

    $.ajax({
          
          
      url: 'relay.php?url=/api/xxx',
      data: data,
      type: 'post',
      dataType: 'json',
      success: function () {
          
          }
    })
    

猜你喜欢

转载自blog.csdn.net/yanzhi_2016/article/details/85695888