在curl请求之后,如何使用第一个请求中的数据发送curl请求?

时间:2018-07-25 12:10:08

标签: php curl request

我想发送两个卷曲请求。 首先:

function auth($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0");
    curl_setopt($ch, CURLOPT_COOKIEFILE, $user_cookie_file);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $user_cookie_file);
    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array(
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
        'Accept-Encoding: gzip, deflate, br',
        'Content-Type: application/x-www-form-urlencoded',
        'Connection: keep-alive',
        'Upgrade-Insecure-Requests: 1',
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $html = curl_exec($ch);
    curl_close($ch);

    $s01 = strpos($html, 'Redirecting', 0);

    if ($s01 === false) {
        echo "Not Found";
        $found_url = '';
    } else {
        echo "Found ";
        if (preg_match('/<a href="(.+)">/', $html, $matches));
        $found_url = $matches[1];

        return $found_url;
    }
}

第二:

function auth1($found_url) {
    $ch = curl_init($found_url);
    curl_setopt($ch, CURLOPT_URL, $found_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0");
    curl_setopt($ch, CURLOPT_COOKIEFILE, $user_cookie_file);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $user_cookie_file);
    curl_setopt($ch, CURLOPT_POST, 0);

    $headers = array(
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
        'Accept-Encoding: gzip, deflate, br',
        'Content-Type: application/x-www-form-urlencoded',
        'Connection: keep-alive',
        'Upgrade-Insecure-Requests: 1',

    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $html = curl_exec($ch);
    echo $html;
    return $html;

}

我想发送两个卷曲请求。发送第一个请求后,我需要从第一个请求中获取$ found_url并发送第二个请求。如何正确实施?我知道这可能是一个愚蠢的问题,但我坚持了下去。

1 个答案:

答案 0 :(得分:1)

通过将返回值添加到“未找到的部分”以返回可能为null或为空,或将返回值移至if语句之外,将第一个auth修改为始终返回某些内容。然后下面的代码应该起作用。

$foundUrl = auth($url);
if($foundUrl){
   $html = auth1($foundUrl);
}