2015-06-23 33 views
2

我無法弄清楚如何在Goutte中設置Cookie。我正在嘗試以下代碼:如何在Goutte中設置Cookie?

$client->setHeader('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36'); 
$client->getCookieJar()->set('SRCHUID'); 

我附上了一個帶有此名稱的cookie的圖像。我怎樣才能設置這個cookie?

enter image description here

+0

如果你找到一個答案,然後請張貼在這裏 – Umair

回答

2

GOUTTE與狂飲6

use GuzzleHttp\Cookie; 

$cookieJar = new \GuzzleHttp\Cookie\CookieJar(true); 

$cookieJar->setCookie(new \GuzzleHttp\Cookie\SetCookie([ 
     'Domain' => "www.domain.com", 
     'Name' => $name, 
     'Value' => $value, 
     'Discard' => true 
])); 

$client = new Client(); 
$guzzleclient = new \GuzzleHttp\Client([ 
     'timeout' => 900, 
     'verify' => false, 
     'cookies' => $cookieJar 
    ]); 
    $client->setClient($guzzleclient); 

    return $client; //or do your normal client request here e.g $client->request('GET', $url); 
1

對我來說,使用GuzzleClient沒有工作。我使用getCookieJar返回的CookieJar。我在最初的問題中看到的唯一錯誤是您嘗試僅通過提供字符串值來設置cookie。 set方法需要Cookie實例才能工作。該方法的簽名是:

/** 
* Sets a cookie. 
* 
* @param Cookie $cookie A Cookie instance 
*/ 
public function set(Cookie $cookie) 

例子:

$this->client->getCookieJar()->set(new Cookie($name, $value, null, null, $domain)); 

小心不要編碼的cookie值或設置encodedValue Cookie的__construct的真實

簽名:

/** 
* Sets a cookie. 
* 
* @param string $name   The cookie name 
* @param string $value  The value of the cookie 
* @param string $expires  The time the cookie expires 
* @param string $path   The path on the server in which the cookie will be available on 
* @param string $domain  The domain that the cookie is available 
* @param bool $secure  Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client 
* @param bool $httponly  The cookie httponly flag 
* @param bool $encodedValue Whether the value is encoded or not 
*/ 
public function __construct($name, $value, $expires = null, $path = null, $domain = '', $secure = false, $httponly = true, $encodedValue = false)