PHP 使用 curl做数据中转

2020-08-06  本文已影响0人  智民

请求流程

  1. 客户端浏览器请求
  2. 后台获取浏览器请求数据,转发到curl中转
    //获取浏览器参数
    $data = [
        'url'=>'需要中转地址',                                //浏览器请求的网址
        'post'=>file_get_contents("php://input"),   //post数据
        'get'=>http_build_query($_GET),             //get数据
        'server'=>$_SERVER                              //服务器头
    ];
    $data=http_build_query($data);//参数的数组转字符串
    $content=curl_post_https('./curl.php',$data);  //取得curl中转返回数据
  1. curl接收后台数据,发起请求,返回给后台

./curl.php 代码如下:

    /**
    * 获取“前端”请求信息,
    * @param  tit  nginx标记的tit
    * @param  url  对方真实网址
    * @param  post  对方post数据
    * @param  get  对方get数据
    * @param  server  “前端”请求头
    * @return array
    */
    function request(){
        $data=[
            'url'=>$_POST['url'],//对方真实网址
            'post'=>$_POST['post'],//post数据
            'get'=>$_POST['get'],//get数据
            'server'=>$_POST['server']   //服务器头网址
        ];
        parse_str($_POST['get'],$data['get']);//get参数转为数组
        // echo json_encode($data,true);exit;//测试输出
        return $data;
    }
    function init() {
        $request=request();

        $r['url']=$request['url'];
        $r['contentType']=$request['server']['HTTP_ACCEPT'];
        $r['method']=$request['server']['REQUEST_METHOD'];;
        $r['cookie']=$request['server']['HTTP_COOKIE'];;
        $r['data']=(strtolower($method)=='get')?$request['get']:$request['post'];
        $r['url']='https://www.readlightnovel.org/the-bumpy-road-of-marriage-the-ex-wife-is-expecting/chapter-449';
        $dataRemote=http_request($r['url'],$r['cookie'],$r['data'],$r['method'],[]);
        // echo json_encode($r,true);exit;//测试输出
        echo $dataRemote;//返回数据给“前端”
    }
    init();
    /**
     * @param $url
     * @param $cookie
     * @param array $data
     * @param $method
     * @param array $headers
     * @return mixed
     */
    function http_request($url, $cookie, $data = array(), $method = 'get', $headers = array()) {
        $method = strtoupper($method);
        $curl = curl_init();
        if(count($data) && $method == "GET"){
            $data = array_filter($data);
            $url .= "?".http_build_query($data);
            $url = str_replace(array('%5B0%5D'), array('[]'), $url);
        }else{
            $data=http_build_query($data);
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        if (count($headers)) {
            $head = array();
            foreach ($headers as $name=>$value) {
                $head[] = $name.":".$value;
            }
            curl_setopt($curl, CURLOPT_HTTPHEADER, $head);
        }
        switch($method) {
            case 'GET':
                break;
            case 'POST':
                $data=http_build_query($data);
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                break;
            case 'PUT':
                $data=http_build_query($data);
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                break;
            case 'DELETE':
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
                break;
        }
        if (!empty($cookie)) curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        // gb2312转码
        if(mb_check_encoding($output, 'GB2312')) $output = mb_convert_encoding($output,'UTF-8','GB2312');
        curl_close($curl);
        return $output;
    }
    /**
    * 判断"前端"是否post
    */
    function isPost($server) {
        return isset($server['REQUEST_METHOD']) ? $server['REQUEST_METHOD'] == 'POST' : false;
    }
    /**
    * 判断"前端"是否ajax
    */
    function isAjax($server){
        if (  isset($server["HTTP_X_REQUESTED_WITH"]) && strtolower($server["HTTP_X_REQUESTED_WITH"]) == 'xmlhttprequest'){
            return true;
        } else {
            return false;
        }
    }
    /**
     * 判断字符串是否为 Json 格式
     *
     * @param  string     $data  Json 字符串
     * @param  bool       $assoc 是否返回关联数组。默认返回对象
     *
     * @return bool|array 成功返回转换后的对象或数组,失败返回 false
     */
    function isJson($data = '', $assoc = false) {
        $data = json_decode($data, $assoc);
        if ($data && (is_object($data)) || (is_array($data) && !empty(current($data)))) {
            return $data;
        }
        return false;
    }
上一篇下一篇

猜你喜欢

热点阅读