统计
  • 建站日期:2021-03-10
  • 文章总数:9403 篇
  • 评论总数:159 条
  • 分类总数:56 个
  • 最后更新:12月11日
文章 未分类

优酷解析源码(参考)

小天
首页 未分类 正文
广告
<?php
$video_info = Youku::parse($url);
echo json_encode($video_info);
/**
*  直接播放地址 http://player.youku.com/embed/XMTg2NDYyNDk4OA 
*/
class Youku
{

    public static function parse($url)
    {
        $content = self::curl($url);
        preg_match("#videoId: '(.*?)',#",$content,$vids1);
        preg_match("#videoId2: '(.*?)',#",$content,$vids2);
        preg_match("#pid: '(.*?)',#",$content,$pid);

        $GLOBALS['ipc']['vid1'] = $vids1[1];
        $GLOBALS['ipc']['vid2'] = $vids2[1];
        $GLOBALS['ipc']['pid']  = $pid[1];
        $GLOBALS['ipc']['url']  = $url;
        $ids = $GLOBALS['ipc'];
        $ids['url'] = $url;
        $ids['referer'] = $url;
        $ids['ccode'] = '0512';
        $ids['vid'] = $vids1[1];
        $ids['P_sck'] = '';
        $ids['m_h5_tk'] = '';
        $ids['m_h5_tk_enc'] = '';
        $ids['ckey'] = 'DIl58SLFxFNndSV1GFNnMQVYkx1PP5tKe1siZu/86PR1u/Wh1Ptd+WOZsHHWxysSfAOhNJpdVWsdVJNsfJ8Sxd8WKVvNfAS8aS8fAOzYARzPyPc3JvtnPHjTdKfESTdnuTW6ZPvk2pNDh4uFzotgdMEFkzQ5wZVXl2Pf1/Y6hLK0OnCNxBj3+nb0v72gZ6b0td+WOZsHHWxysSo/0y9D2K42SaB8Y/+aD2K42SaB8Y/+ahU+WOZsHcrxysooUeND'; //优酷默认key

        return self::get_video_url($ids);
    }
    private static function get_video_url($ids){
        $content = self::get_tv_data($ids);
        //print_r($content);exit;
        $json = json_decode($content,true);

        $data = $json["data"];

        $ids['title'] = $data['video']['title'];

        $stream = $data["stream"];
        //print_r($stream);exit;

        $GLOBALS['ipc']['pay']  = $data["show"]['pay']; //1为收费视频 0为免费视频

        if ($data["show"]["pay"] == 1) {
            $videoinfo['code'] = 302;
            $videoinfo['msg'] = $ids['title'] . ' - 视频正在加载···请稍后···';
            $videoinfo['url'] = '../yun/?url='.$ids['url']; 
            return $videoinfo;exit;
        }

        $point = $data["dvd"]["point"];

        $preview = $data['preview']['thumb'];

        if (!empty($point)) {

            $_tmp['words'] = $_tmp['time'] = '';

            foreach ($point as $key => $value) {
                if (self::filterGBK_SpecialChars($value['title']) == '') {
                    continue;
                }
                $_tmp['words'] .= self::filterGBK_SpecialChars($value['title']).',';
                $_tmp['time'] .= (int)($value['start']/1000).',';
            }
            $_tmp['words'] = substr($_tmp['words'],0,strlen($_tmp['words'])-1);
            $_tmp['time'] = substr($_tmp['time'],0,strlen($_tmp['time'])-1);
            $GLOBALS['ipc']['data']["prompt"] = $_tmp;
            $videoinfo["data"]["prompt"] =     $GLOBALS['ipc']['data']["prompt"];
        }

        foreach ($stream as $key => $value) {
            $stream_type = $value["stream_type"];
            //print_r($stream_type);

            if($stream_type=="3gphd"||$stream_type=="flvhd"){//过滤 
                    continue;
            }
            switch ($stream_type) {
                case  "mp5hd4":     $type = 'mp5';$def = '4K';          break;  # 3840x1638
                case  "mp4sd":        $type = "mp4";$def = "普清";            break;# 640x360
                case  "mp4hd2":        $type = "flv";$def = "FLV超高清";    break;# 1280x720
                case  "mp4hd3":        $type = "flv";$def = "FLV原画";        break;# 1920x1080
                case  "3gphd":        $type = "mp4";$def = "3GP高清";        break;# 640x360
                case  "flvhd":        $type = "flv";$def = "FLV高清";        break;# 640x360
                case  "mp4hd2v2":    $type = "mp4";$def = "超清";            break;# 1280x720
                case  "mp4hd":        $type = "mp4";$def = "高清";            break;# 960x540
                case  "mp4hd3v2":    $type = "mp4";$def = "原画";            break;# 1920x1080
                case  "mp5sd":        $type = "mp4";$def = "MP5高清";        break;# 640x360
                case  "mp5hd2":        $type = "mp4";$def = "MP5超高清";    break;# 1280x720
                case  "mp5hd3":        $type = "mp4";$def = "MP5原画";        break;# 1920x1080
                case  "mp5hd":        $type = "mp4";$def = "MP5超清";        break;# 960x540
            }
            $m3u8 = $value["m3u8_url_backup"];//m3u8文件地址
            if (GlobalBase::is_ipad()) {
                if ($stream_type == 'mp4hd' && $m3u8 != '') {
                     $fdata[1]['url'] = $m3u8;
                     $fdata[1]['def'] = 'mp4高清';
                 }
                if($stream_type=='mp5hd'){
                    $fdata[2]['url'] = $m3u8;
                     $fdata[2]['def'] = 'mp5高清';
                }
                if($stream_type=='mp4sd'){
                    $fdata[2]['url'] = $m3u8;
                     $fdata[2]['def'] = 'mp4标清';
                }
             }else{
                 if ($stream_type == 'mp5hd4' && $m3u8 != '') {
                     $fdata[0]['url'] = $m3u8;
                     $fdata[0]['def'] = '4k';
                 } 
                 if ($stream_type == 'mp5hd3' && $m3u8 != '') {
                     $fdata[1]['url'] = $m3u8;
                     $fdata[1]['def'] = 'mp5原画';
                 }
                 if ($stream_type == 'mp4hd3v2' && $m3u8 != '') {
                     $fdata[2]['url'] = $m3u8;
                     $fdata[2]['def'] = 'mp4原画';
                 }
                 if ($stream_type == 'mp4hd3' && $m3u8 != '') {
                     $fdata[3]['url'] = $m3u8;
                     $fdata[3]['def'] = 'flv原画';
                 }
                 if ($stream_type == 'mp5hd2' && $m3u8 != '') {
                     $fdata[4]['url'] = $m3u8;
                     $fdata[4]['def'] = 'mp5超高清';
                 }
                 if ($stream_type == 'mp4hd2v2' && $m3u8 != '') {
                     $fdata[5]['url'] = $m3u8;
                     $fdata[5]['def'] = 'mp4超高清';
                 }
                 if ($stream_type == 'mp4hd2' && $m3u8 != '') {
                     $fdata[6]['url'] = $m3u8;
                     $fdata[6]['def'] = 'flv超高清';
                 }
                 if ($stream_type == 'mp5hd' && $m3u8 != '') {
                     $fdata[7]['url'] = $m3u8;
                     $fdata[7]['def'] = 'mp5高清';
                 }
                 if ($stream_type == 'mp4hd' && $m3u8 != '') {
                     $fdata[8]['url'] = $m3u8;
                     $fdata[8]['def'] = 'mp4高清';
                 }
                 if ($stream_type == 'flvhd' && $m3u8 != '') {
                     $fdata[9]['url'] = $m3u8;
                     $fdata[9]['def'] = 'flv高清';
                 }
                 if ($stream_type == 'mp4sd' && $m3u8 != '') {
                     $fdata[10]['url'] = $m3u8;
                     $fdata[10]['def'] = 'mp4标清';
                 }

             }
        }
        for ($i=1; $i <= 10 ; $i++) { 
            if ($fdata[$i] == '') {
                continue;
            }
            $key_arrays[]=$fdata[$i];
        }

        $_d = self::is_video_url($key_arrays[0]['url'],$ids['url']);
        if (!empty($_d['type'])&&$_d['type'] == 'url') {
            $videoinfo['code'] = 302;
            $videoinfo['url'] = '../yun/?url='.$ids['url'];
        } else {
            $videoinfo['code'] = 200;
            $videoinfo['play'] = '';
            $videoinfo['msg'] = '解析正常';
            if (GlobalBase::is_ipad()) {
                $videoinfo['data']['url'] = $_d['m3u8'];
            }
            $videoinfo["data"]["video"]["type"] = "video/m3u8";
            $videoinfo["data"]['video']['file'] = $_d['m3u8'];
        }

        $videoinfo["data"]["poster"] = !empty($data['show']['show_thumburl_huge']) ? $data['show']['show_thumburl_huge'] : $data['show']['show_thumburl_big_jpg'];
        $videoinfo["data"]['title'] = !empty($data['video']['title']) ? $data['video']['title'] : $data['show']['title'];
        return $videoinfo;
    }

    public static function get_h5_data($ids)
    {
        $vid = $ids['vid'];
        $ckey = urlencode("DIl58SLFxFNndSV1GFNnMQVYkx1PP5tKe1siZu/86PR1u/Wh1Ptd+WOZsHHWxysSfAOhNJpdVWsdVJNsfJ8Sxd8WKVvNfAS8aS8fAOzYARzPyPc3JvtnPHjTdKfESTdnuTW6ZPvk2pNDh4uFzotgdMEFkzQ5wZVXl2Pf1/Y6hLK0OnCNxBj3+nb0v72gZ6b0td+WOZsHHWxysSo/0y9D2K42SaB8Y/+aD2K42SaB8Y/+ahU+WOZsHcrxysooUeND");
        $ccode = "0502";//0502
        $cna = self::fetch_cna();
        $utid = urlencode($cna);
        $client_ip = "0.0.0.0";
        $url = "https://ups.youku.com/ups/get.json?vid=$vid&ccode=$ccode&client_ip=$client_ip&utid=$utid&client_ts=".time()."&ckey=".$ckey."&rst=mp4&dq=mp4&os=ios&bt=phone";
        $ids['cookie'] = COOKIE_YOKU;
        $content = self::curl($url,$ids);
        return $content;
    }
    public static function get_ups_data($ids) //ups接口需P_sck ccode = 0510
    {
        $ckey = urlencode($ids['ckey']);
        $ids['ccode'] = "0510";//01010203  var ccodes = []string{"0510", "0502", "0507", "0508", "0512", "0513", "0514", "0503", "0590"}
        $ids['utid'] = urlencode(self::fetch_cna());
        $ids['client_ip'] = "192.168.1.1";
        $ids['cookie'] = COOKIE_YOKU;
        $url = "https://ups.youku.com/ups/get.json?vid=".$ids['vid']."&ccode=".$ids['ccode']."&client_ip=".$ids['client_ip']."&utid=".$ids['utid']."&client_ts=".time()."&ckey=".$ckey;
        $content = self::curl($url,$ids);
        return $content;
    }

    public static function get_ups1_data($ids) //ups接口需P_sck ccode = 0502
    {
        //print_r($ids);exit;
        $vid = $ids['vid'];
        $ids['ua'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:49.0) Gecko/20100101 Firefox/49.0';
        $ids['re'] = 'http://v.youku.com/v_show/id_{$ids["vid"]}.html';
        $ids['cookie'] = COOKIE_YOKU;
        $ckey = urlencode($ids['ckey']);
        $ccode = "0502";//01010203  var ccodes = []string{"0510", "0502", "0507", "0508", "0512", "0513", "0514", "0503", "0590"}
        $utid = urlencode(self::fetch_cna());
        $client_ip = "192.168.1.1";
        $url = "https://ups.youku.com/ups/get.json?vid=$vid&ccode=$ccode&client_ip=$client_ip&utid=$utid&client_ts=".time()."&ckey=".$ckey;
        $content = self::curl($url,$ids);
        return $content;
    }

    public static function get_acs_data($ids) //acs接口需P_sck,_m_h5_tk,_m_h5_tk_enc  sign = u = s(n.token + "&" + l + "&" + o + "&" + i.data), s为md5
    {
        $ids['appKey'] = '24679788';
        $ids['jsv'] = '2.4.11';
        $ids['sign'] = '3a75b723ce917983c363380b679d3e68';
        $ids['t'] = '1531605637237';
        $ids['api'] = 'mtop.youku.play.ups.appinfo.get';
        $ids['v'] = '1.1';
        $ids['timeout'] = 20000;
        $ids['YKPid'] = '20160317PLF000211';
        $ids['YKLoginRequest'] = true;
        $ids['AntiFlood'] = true;
        $ids['AntiCreep'] = true;
        $ids['type'] = 'jsonp';
        $ids['dataType'] = 'jsonp';
        $ids['callback'] = 'mtopjsonp1';

        $api = 'https://acs.youku.com/h5/mtop.youku.sports.data.match.getbyliveid/1.0/?jsv=2.4.11&appKey=24679788&t=1531610612473&sign=5698a52fa17ae7f0e72c6176fbb511f3&api=mtop.youku.sports.data.match.getbyliveid&v=1.0&type=jsonp&dataType=jsonp&callback=mtopjsonp2&data=%7B%22liveId%22%3A%228001964%22%7D';

        $ids['ua'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36';
        $ids['cookie'] = COOKIE_YOKU.'_m_h5_tk=593a55d21c5b77869446fde46b0ecf6a_1531609950094; _m_h5_tk_enc=3e3afff2bae27d37be77813045995957;';

        $ckey = urlencode("DIl58SLFxFNndSV1GFNnMQVYkx1PP5tKe1siZu/86PR1u/Wh1Ptd+WOZsHHWxysSfAOhNJpdVWsdVJNsfJ8Sxd8WKVvNfAS8aS8fAOzYARzPyPc3JvtnPHjTdKfESTdnuTW6ZPvk2pNDh4uFzotgdMEFkzQ5wZVXl2Pf1/Y6hLK0OnCNxBj3+nb0v72gZ6b0td+WOZsHHWxysSo/0y9D2K42SaB8Y/+aD2K42SaB8Y/+ahU+WOZsHcrxysooUeND");
        $ccode = "0510";//01010203  var ccodes =0401 []string{"0510", "0502", "0507", "0508", "0512", "0513", "0514", "0503", "0590"}
        $utid = urlencode(self::fetch_cna());
        $client_ip = "192.168.1.1";
        $url = "https://ups.youku.com/ups/get.json?vid=$vid&ccode=$ccode&client_ip=$client_ip&utid=$utid&client_ts=".time()."&ckey=".$ckey;
        $content = self::curl($url,$ids);
        return $content;
    }

    public static function get_tv_data($ids)  //电视解析接口
    {
        $vid= $ids['vid'];
        $ckey = urlencode("7B19C0AB12633B22E7FE81271162026020570708D6CC189E4924503C49D243A0DE6CD84A766832C2C99898FC5ED31F3709BB3CDD82C96492E721BDD381735026");
        $ccode = "0103010102"; //0103010102
        $utid = 'WgLG5mr8ST8DAKRFhImwwCov';

        $client_ip = "192.168.1.1";
        $url = "https://ups.cp31.ott.cibntv.net/ups/get.json?vid=$vid&ccode=$ccode&client_ip=$client_ip&utid=$utid&client_ts=".time()."&ckey=".$ckey;
        $ids['cookie'] = '';
        $ids['ua'] = 'OTTSDK;2.0.3.73;Android;4.4.2;oppo R11';
        //print_r($url);exit;
        $content = self::curl($url,$ids);
        return $content;
    }

    public static function get_atv_data($ids)  //电视蓝光资源解析
    {
        $vid = $ids['vid'];
        $ckey = urlencode("7B19C0AB12633B22E7FE81271162026020570708D6CC189E4924503C49D243A0DE6CD84A766832C2C99898FC5ED31F3709BB3CDD82C96492E721BDD381735026");  //ckey_mobile
        $ccode = "0103010102";
        $utid = 'VocTAztMueMDAGTMB5pNW/2V';
        $ids['ua'] = 'OTTSDK;2.0.3.73;Android;5.1;vivo X6D';
        $params = array(
            'ckey' => $ckey,
            'client_ip' => '192.168.1.1',
            'client_ts'  => time(),
            'utid' => $utid,
            'ccode' => $ccode,
            'encryptR_client' => 'AdqPCJSQ0zBM8K8xbPj2LQ==',
            'key_index' => 'key01',
            'vid' => $vid,
            'tmall_pid' => 'f456ab7ea7944c4b',
            'h265' => 1,
            'client_id' => '',
            'ptoken' => '',
            'stoken' => '',
            'atoken' => '',
            'mac' => 'FC1A113ACD4C',
            'app_ver' => '2120513101',
            'drm_type' => 7,
            'needad' => 0,
            'needbf' => 1,
            'site' => 1,
            'fu' => 1,
            'wintype' => 'mdevice',
            'vs' => '1.0',
            'os' => 'Android',
            'osv' => '5.1',
            'bt' => 'tv',
            'aw' => 'a',
            'rst' => 'm3u8',
            'p' => 27,
            'bd' => 'vivo',
            'guid' => '6ac02a7008d8089ba4a75cb274e7bd39',
            'net' => 1000,
            'pid' => 'f456ab7ea7944c4b',
            'mdl' => 'TVADSDK_Device',
            'dvw' => 1920,
            'dvh' => 1080,
            'dprm' => 480,
            'box' => 1,
            'aid' => 'e09b8c1acd56c2e2',
            'ss' => '5.2',
            'isvert' => 0,
            'uuid' => 'A4F6815D175ACF602D7E4409DDB37467'
        );

        $api = 'https://ups.cp31.ott.cibntv.net/ups/get.json?' . http_build_query($params);

        $data = self::curl($api,$ids);

        return $data;
    }

    public static function filterGBK_SpecialChars($str)
    {
        $str = str_replace('“','',$str);
        $str = str_replace('”','',$str);
        $str = str_replace('"','',$str);
        $str = str_replace(' ','',$str);
        return $str;
    }
    public static function is_video_url($url,$a){

        $data = self::curl($url,$ids='');

        //print_r($data);exit;

        if(strstr($data,"http")==true || strstr($data,".ts")==true){
            $d['m3u8'] = "../video/m3u8.php?url=m3u8".base64_encode($url);
        } else {
            $d['m3u8'] = '../yun/?url='.$a;
            $d['type'] = 'url';
        }
                return $d;

    }
    public static function curl($url,$ids)
    {
        $params["ua"] = !empty($ids['ua'])?$ids['ua']:"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36";
        $params['ref'] = isset($ids['referer']) ? $ids['referer'] : $ids['url'];
        $params["cookie"] = !empty($ids['cookie']) ? $ids['cookie'] : '' ;
        $params["ip"] = isset($ids['ip']) ? $ids['ip'] : "14.21.96.129";//伪装为固定IP,否则会报异地登录,会封号,不要更改
          return GlobalBase::curl($url,$params);
    }
    public static function fetch_cna()
    {
        $url = 'http://gm.mmstat.com/yt/ykcomment.play.commentInit?cna=';
        $request = new Request();
        $request->http_get($url);
        $values = $request->get_res_header('Set-Cookie');
        $cna = false;
        foreach ($values as $value) {
            preg_match('/cna=([^;]+)/', $value, $matches);
            if (count($matches) > 0) {
                $cna = $matches[1];
                break;
            }
        }
        if (!$cna) {
            $cna = 'oqikEO1b7CECAbfBdNNf1PM1';
        }
        return $cna;
    }
}
/**
* 
*/
class Cna
{

    public static function get_signature($str)
    {
        $signature = "";
        $key="d6fc3a4a06adbde89223bvefedc24fecde188aaa9161";
        if (function_exists('hash_hmac'))
        {
            $signature = base64_encode(hash_hmac("sha1", $str, $key, true));
        }else{
            $blocksize    = 64;
            $hashfunc    = 'sha1';
            if (strlen($key) > $blocksize){ $key = pack('H*', $hashfunc($key));}
            $key    = str_pad($key,$blocksize,chr(0x00));
            $ipad    = str_repeat(chr(0x36),$blocksize);
            $opad    = str_repeat(chr(0x5c),$blocksize);
            $hmac     = pack('H*',$hashfunc(($key^$opad).pack('H*',$hashfunc(($key^$ipad).$str))));
            $signature = base64_encode($hmac);
        }
        return $signature;
    }
    public static function utid()
    {
        $str = mt_rand(-2147483648,2147483648);
        $i = time();
        $j = mt_rand(-2147483648,2147483648);
        $arrayOfByte1 = self::aa($i);
        $arrayOfByte2 = self::aa($j);
        $arr = array_merge($arrayOfByte1,$arrayOfByte2);
        $arr[count($arr)]= 3;
        $arr[count($arr)]= 0;
        $arr = array_merge($arr,self::aa(self::ca($str)));
        $sign = self::get_signature(self::ba($arr));
        $arr = array_merge($arr,self::aa(self::ca($sign)));
        return base64_encode(self::ba($arr));
    }
    public static function  ca($paramString)
    {
        $i = 0;$k = 0;
        if (strlen($paramString) <= 0) {return $k;}
        $param = str_split($paramString);
        $arr = array();
        for ($n=0; $n < count($param); $n++) { 
            $arr[$n]= ord($param[$n]);
        }
        $j = 0;
        while (true) {
            $k = $i;
            if ($j >= count($arr)) {break;}
            $i = self::intval32($i * 31 + $arr[$j]);
            $j += 1;
        }
        return $k;
    }
    public static function aa($paramInt)
    {
        $i = $paramInt % 256;
        $j = ($paramInt >>= 8) % 256;
        $k = ($paramInt >>= 8) % 256;
        $n = ($paramInt >> 8) % 256;
        $arr =  array($n, $k, $j, $i);
        return $arr;
    }
    public static function ba($arr)
    {
        $str = "";
        for ($i=0; $i <count($arr) ; $i++) { 
            $str .= chr($arr[$i]);
        }
        return $str;
    }
    public static function intval32($num) {
        $num = $num & 0xffffffff;
        $p = $num>>31;
        if($p==1) {
            $num = $num-1;
            $num = ~$num;
            $num = $num & 0xffffffff;
            return $num * -1;
        } else {
            return $num;
        }
    } 
}

class Request
{
    public $info;
    public $req_cookies;
    public $full_url;
    public $response;
    public $header;
    public $response_headers = array();
    public $body;
    public function merge_default_header($headers)
    {
        $defaults = array(
            'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language' => 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Accept-Encoding' => 'gzip, deflate',
            'cache-control' => 'no-cache',
            'User-Agent' => "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.2.1"
        );
        $array_merge = array_merge($defaults, $headers);
        return $array_merge;
    }
    /**
     * GET 请求
     * @param string $url
     */
    public function http_get($url, $params = array(), $cookies = array(), $headers = array())
    {
        $this->full_url = $url;
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_HEADER, TRUE);//至关重要,CURLINFO_HEADER_OUT选项可以拿到请求头信息
        curl_setopt($oCurl, CURLINFO_HEADER_OUT, TRUE);//请求头信息
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        // curl_setopt($oCurl, CURLOPT_NOBODY, TRUE);// 不获取body
        curl_setopt($oCurl, CURLOPT_ENCODING, "");
        // 参数
        if (is_array($params)) {
            $params_str = $this->get_params_str($params);
            if (strpos($this->full_url, '?') === FAlSE) {
                $this->full_url .= '?' . $params_str;
            } else {
                $this->full_url .= '&' . $params_str;
            }
        }
        // cookies
        if (is_array($cookies)) {
            $cookies_str = $this->get_cookies_str($cookies);
            curl_setopt($oCurl, CURLOPT_COOKIE, $cookies_str); //使用cookies
        }
        // headers
        $headers = $this->merge_default_header($headers);
        $headers = self::flatten($headers);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($oCurl, CURLOPT_URL, $this->full_url);
        $response = curl_exec($oCurl);
        $this->info = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($this->info["http_code"]) == 200) {
            $this->process_response_headers($response);
            return $response;
        } else {
            return false;
        }
    }
    public function process_response_headers($response)
    {
        $header_size = $this->info['header_size'];
        $this->header = substr($response, 0, $header_size);
        $this->body = substr($response, $header_size);
        $headArr = explode("rn", $this->header);
        foreach ($headArr as $line) {
            preg_match('/(.*?):(.+)/', $line, $matches, PREG_OFFSET_CAPTURE);
            if (count($matches) == 3) {
                $key = trim($matches[1][0]);
                $this->response_headers[] = array($key => trim($matches[2][0]));
                /*if (isset($this->response_headers[$key])) {
                    $this->response_headers[$key] .= ';' . trim($matches[2][0]);
                } else {
                    //$this->response_headers[$key] = trim($matches[2][0]);
                }*/
                // var_dump($matches);
                // echo "<br>";
                /*
                array (size=3)
                  0 =>
                    array (size=2)
                      0 => string 'Date: Thu, 22 Mar 2018 07:35:59 GMT' (length=35)
                      1 => int 0
                  1 =>
                    array (size=2)
                      0 => string 'Date' (length=4)
                      1 => int 0
                  2 =>
                    array (size=2)
                      0 => string ' Thu, 22 Mar 2018 07:35:59 GMT' (length=30)
                      1 => int 5
                 */
            }
        }
    }
    public function get_res_header($key)
    {
        $arr = array();
        foreach ($this->response_headers as $header) {
            if (isset($header[$key])) {
                $arr[] = $header[$key];
            }
        }
        return $arr;
    }
    private function arr_join_str($arr, $separator)
    {
        $str = '';
        foreach ($arr as $key => $value) {
            $str .= $key . '=' . $value . $separator;
        }
        $str = substr($str, 0, strlen($str) - strlen($separator));
        return $str;
    }
    public function get_params_str($params)
    {
        return $this->arr_join_str($params, '&');
    }
    public function get_cookies_str($cookies_arr)
    {
        return $this->arr_join_str($cookies_arr, ';');
    }
    public static function flatten($array)
    {
        $return = array();
        foreach ($array as $key => $value) {
            $return[] = sprintf('%s: %s', $key, $value);
        }
        return $return;
    }
}

?>

版权说明
文章采用: 《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权。
版权声明:未标注转载均为本站原创,转载时请以链接形式注明文章出处。如有侵权、不妥之处,请联系站长删除。敬请谅解!

-- 展开阅读全文 --
这篇文章最后更新于2021-10-11,已超过 1 年没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!
大数据面试题-hdfs读写流程
« 上一篇
数仓中的全量表,增量表,拉链表,流水表,快照表
下一篇 »

发表评论

HI ! 请登录
注册会员,享受下载全站资源特权。
社交账号登录

热门文章