V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
awanganddong
V2EX  ›  PHP

guzzle 爬取数据, 302 后怎么获取 sessionid

  •  
  •   awanganddong · 2020-12-28 20:34:46 +08:00 · 1699 次点击
    这是一个创建于 1207 天前的主题,其中的信息可能已经有所发展或是发生改变。
             $response = $client->request('GET', self::$jumpUrl, [
                    'cookies' => $cookieJar,
                    'query' => [
                        'tochannelid' => $channelId
                    ],
                    'allow_redirects' => [
                        'max' => 5,        // allow at most 10 redirects.
                        'track_redirects' => true
                    ],
                    'debug' => true
                ]);
                $lastRedirectArr = $response->getHeaders()['X-Guzzle-Redirect-History'];
                list($code, $msg) = $this->getCookie($lastRedirectArr[1]);
                
                $client = new Client();
                $res = $client->request('GET', $url);
                $header = $res->getHeaders();
    

    通过主账号登录跳转获取子账号的 cookie,实现子账号登录。

    现在问题是通过主账号,获取不到 302 后的 cookie

    打开 debug,是存在正确 cookie 的 我获取最后的跳转链接,然后再次请求,获取到的 cookie 是错误的。

    现在不知道问题哪里

    2 条回复    2020-12-31 09:14:53 +08:00
    ben1024
        1
    ben1024  
       2020-12-29 10:55:25 +08:00
    多次重定向?
    找个能获取的点进行存储起来用
    awanganddong
        2
    awanganddong  
    OP
       2020-12-31 09:14:53 +08:00
    guzzle 自身的重定向功能好像不支持携带 cookie,需要手动来进行 redirect 跳转。
    1.关闭 allow_redirects (关闭字段重定向)
    2.判断$response 是否是 302
    3.如果是重定向
    4.则请求这个回调函数

    ```
    public function callback($redirect, $cookie)
    {
    $client = new Client();
    $response = $client->request('GET', $redirect, [
    'headers' => [
    'Cookie' => $cookie,
    ],
    'allow_redirects' => false
    ]);
    if ($response->getStatusCode() === 302) {
    $redirect = $response->getHeaderLine('Location');
    $cookie = $response->getHeaderLine('Set-Cookie') ?? $cookie;
    if (strpos($redirect, 'http') === false) {
    $redirect = self::$adminBaseLink . $redirect;
    }
    $cookie = $this->callback($redirect, $cookie);
    }
    $cookie = $response->getHeaderLine('Set-Cookie') ?? $cookie;
    return $cookie;
    }
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1045 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 19:15 · PVG 03:15 · LAX 12:15 · JFK 15:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.