Pedro Lobito
Pedro Lobito

Reputation: 99011

Selenium Cookie to Curl Cookie

How to convert a cookie saved by selenium (driver.get_cookies()) to a cookie that can be used with curl ?

The content o selenium cookie when dumped to a text file looks like this:

[{u'domain': u'.site.com', u'name': u'NID', u'value': u'somelooooooooooongvalue', u'expiry': 1443722412, u'path': u'/', u'secure': False}, {u'domain': u'.site.com', u'name': u'SID', u'value': u'somelooooooooooooooongvalue', u'expiry': 1490983212, u'path': u'/', u'secure': False}]

Is there any way to achieve this?

Upvotes: 0

Views: 1955

Answers (1)

Pedro Lobito
Pedro Lobito

Reputation: 99011

I managed to solve this with a regex.

Example cookies dumped from selenium with driver.get_cookies():

$seleniumCookies = "[{u'domain': u'.site.com', u'name': u'NID', u'value': u'somelooooooooooongvalue', u'expiry': 1443722412, u'path': u'/', u'secure': False}, {u'domain': u'.site.com', u'name': u'SID', u'value': u'somelooooooooooooooongvalue', u'expiry': 1490983212, u'path': u'/', u'secure': False}]";

$curlCookies = "";

preg_match_all('/\'name\': u\'(.*?)\', u\'value\': u\'(.*?)\'/i', $seleniumCookies, $matches, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($matches[0]); $i++) {
    $name =  $matches[1][$i];
    $value =  $matches[2][$i];

    $curlCookies .= "$name=$value;";

}

The $curlCookies var now looks like this :

NID=somelooooooooooongvalue;SID=somelooooooooooooooongvalue;

Now we can make the curl request using the $curlCookies inside the CURLOPT_HTTPHEADER:

$url =  "https://some.host.com/that-need-selenium-cookies";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Host: some.host.com:443",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language: en-US,en;q=0.8",
"Cookie: $curlCookies"
));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_ENCODING, "");
$pagebody=curl_exec ($ch);
curl_close ($ch);

That's it, the code works perfectly. I hope this helps others.

Upvotes: 1

Related Questions