<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

// +----------------------------------------------------------------------
// curl方法
// +----------------------------------------------------------------------

/**
 * get 请求
 * @param $url
 * @param array $params
 * @param string $cookie
 * @return array
 */
function get_url($url, $params = [], $cookie = "")
{
    if ($params) {
        $url = $url . '?' . http_build_query($params);
    }
    $curl = new \network\CurlHelper($url);
    $curl->setCookie($cookie);
    $curl->exec();
    return [$curl->getResponse(), $curl->getHttpCode(), $curl->getError()];
}

/**
 * post 请求
 * @param $url
 * @param array $params
 * @param array $header
 * @param string $cookie
 * @return array
 */
function post_url($url, $params = [], $header = [], $cookie = "")
{
    $curl = new \network\CurlHelper($url, $params);
    $curl->setHeader($header);
    $curl->setCookie($cookie);
    $curl->exec();
    return [$curl->getResponse(), $curl->getHttpCode(), $curl->getError()];
}

/**
 * 提交json格式的请求
 * @param $url
 * @param array $params
 * @return array
 */
function post_json($url, $params = [])
{
    $header = ['Content-Type: application/json; charset=utf-8', 'Content-Length:' . strlen(json_encode($params))];
    $curl = new \network\CurlHelper($url, json_encode($params));
    $curl->setHeader($header);
    $curl->exec();
    return [$curl->getResponse(), $curl->getHttpCode(), $curl->getError()];
}


/**
 * 有的接口会通过cookie防采集
 * @param $url
 * @param $expire int 默认缓存一小时
 * @return mixed
 * @throws Exception
 */
function get_by_set_cookie($url, $expire = 3600)
{
    $cookieName = "cache-setcookie-key";
    $cookieVal = isset($_COOKIE[$cookieName]) ? $_COOKIE[$cookieName] : "";
    list($response, $httpCode) = get_url($url, [], $cookieVal);
    if ($httpCode == 302) {
        $curl = new \network\CurlHelper($url);
        $curl->showResponseHeader();//输出响应头
        $curl->exec();
        $response = $curl->getResponse();
        // 正则获取set-cookie
        if (preg_match_all('/Set-Cookie: (.*?);/m', $response, $cookie)) {
            $realCookie = implode(';', $cookie['1']);
            setcookie($cookieName, $realCookie, time() + $expire);//缓存
            list($response) = get_url($url, [], $cookieVal);
        } else {
            throw new Exception("获取Set-Cookie失败");
        }
    } else if ($httpCode == 301) {
        throw new Exception("获取失败，返回301跳转");
    } else if ($httpCode != 200) {
        throw new Exception("获取失败，httpCode = $httpCode");
    }
    return $response;
}

