1

Possible Duplicate:
how to get the cookies from a php curl into a variable

I have the code below running and what it does is get a web page using curl. My problem is when it gets the web page it doesnt get the cookies from the site.

   $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, ''.$stuff_link[0].'');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, false);
    $html = curl_exec($ch);
    curl_close ( $ch );
    echo $html;

I tried a few thing none of which worked.

Community
  • 1
  • 1
user2002220
  • 115
  • 1
  • 1
  • 10

2 Answers2

6
$ch = curl_init('http://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get headers too with this line
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
// get cookie, all cos sometime set-cookie could be more then one
preg_match_all('/^Set-Cookie:\s*([^\r\n]*)/mi', $result, $ms);
// print_r($result);
$cookies = array();
foreach ($ms[1] as $m) {
    list($name, $value) = explode('=', $m, 2);
    $cookies[$name] = $value;
}
print_r($cookies);
Kerem
  • 11,377
  • 5
  • 59
  • 58
  • thanks with this it prints the cookies but they are not set in my browser – user2002220 Jan 25 '13 at 02:56
  • Yes, true. The server (URL) trying to set cookies but can't, cos cookies go to CURL (in simple saying). So it's same with this (command line): `curl -v http://google.com/`. But if you open URL with your browser these cookies will be set on your browser. – Kerem Jan 25 '13 at 04:46
0

try this:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "HTTP://URLHERE.COM");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
$html = curl_exec($ch);
preg_match('/^Set-Cookie: (.*?);/m', curl_exec($ch), $m);
var_dump(parse_url($m[1]));
curl_close ( $ch );
echo $html;

Duplicate question pretty much from: how to get the cookies from a php curl into a variable

Community
  • 1
  • 1
Mark
  • 2,423
  • 4
  • 24
  • 40