lang/php

PHP Goutte Cookie

C/H 2018. 7. 1. 08:30

composer.json

{
    "require": {
        "fabpot/goutte": "^3.2"
    }
}

Cookie 정보 확인

require 'vendor/autoload.php';

use Goutte\Client;

$url = 'https://github.com/login';

$client = new \Goutte\Client();
$client->setClient(new \GuzzleHttp\Client([ 'timeout' => 90, 'verify' => false, 'cookie'=>true ]));

$crawler = $client->request('GET', $url);
echo $crawler->filterXPath('html/head/title')->text()."\n";
echo $crawler->getUri()."\n";

$form = $crawler->selectButton('Sign in')->form();
$form['login'] = 'username@domain.com';
$form['password'] = 'password';
$crawler = $client->submit($form);
// $crawler = $client->submit($form, ['login'=>'username@domain.com', 'password'=>'password']);
echo $crawler->filterXPath('html/head/title')->text()."\n";
echo $crawler->getUri()."\n";

// cookie
$cookies = $client->getCookieJar();
var_dump( (array)$cookies->all() );

name 으로 쿠키자료 확인

// logged_in cookie
$cookie = $client->getCookieJar()->get('logged_in');    // logged_in cookie
$name       = $cookie->getName();
$value      = $cookie->getValue();
$rawValue   = $cookie->getRawValue();
$isSecure   = $cookie->isSecure();
$isHttpOnly = $cookie->isHttpOnly();
$isExpired  = $cookie->isExpired();
$expires    = $cookie->getExpiresTime();
$path       = $cookie->getPath();
$domain     = $cookie->getDomain();

var_dump($name, $value, $rawValue, $isSecure, $isHttpOnly, $isExpired, $expires, $path, $domain);

도메인으로 Cookie 확인

$cookieJar = $client->getCookieJar();

// Get array with all cookies
$cookies = $cookieJar->all();
foreach ($cookies as $cookie) {
    print_r($cookie);
}

// Get all values
$values = $cookieJar->allValues('http://symfony.com');
foreach ($values as $value) {
    print_r($value);
}

// Get all raw values
$rawValues = $cookieJar->allRawValues('http://symfony.com');
foreach ($rawValues as $rawValue) {
    print_r($rawValue);
}

Cookie 설정

$cookies = $client->getCookieJar()->all(); // 쿠키를 얻고, $client2 = new Client(); // 새로운 클라이언트 $client2->getCookieJar()->updateFromSetCookie($cookies); // 쿠키를 설정 $crawler2 = $client2->request('get', $url); echo $crawler2->filterXPath('html/head/title')->text()."\n"; echo $crawler2->getUri()."\n";


반응형

'lang > php' 카테고리의 다른 글

PHP simple-html-dom-parser  (0) 2018.07.03
PHP Gouttle DomCrawler Component  (0) 2018.07.02
PHP Guzzle Scraper  (0) 2018.06.30
Simple PHP Web Scraper Guotte  (0) 2018.06.29
PHP Laravel Framework helloWorld  (0) 2018.06.15