How to Get the Cookies from a PHP Curl into a Variable

how to get the cookies from a php curl into a variable

$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
// multi-cookie variant contributed by @Combuster in comments
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
var_dump($cookies);

How to stock my cookies from a curl request on a variable

I solve my problem by using regex on the request result. and use CURLOPT_COOKIE.

// Execute the request
$response = curl_exec($ch);
// Extract the cookie from the answer
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $response, $matches);
$cookies = $matches[1][0];
// Extract the server response from the answer
preg_match_all('/text\/html\s*(.*)/m', $response, $matches);
$serverResponse = json_decode($matches[1][0]);

PHP & cURL: is it possible to get a cookie into variable instead of file without parsing headers?

Lets try this with a single curl handle($ch):

Making my first request:

$url= "http://www.google.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, '-'); // <-- see here
$result = curl_exec($ch);

// remember i didn't close the curl yet!

Now make another curl request with the same handle:

$url= "http://www.google.com";
curl_setopt($ch, CURLOPT_URL,$url);
$result = curl_exec($ch);
// if you are done, you can close it.
curl_close($ch);

In this example, I have used the - for the cookiejar. Which means it will not use any file. So during second curl request, it will use the cookiejar of previous call.

One problem: It will print the cookie jar values into std-output.

How to get cookie from remote webpage using PHP cURL?

There are two ways(may be more) you can do this.

Using the cookie file:

$cookie_file = 'e:/demo/cookies.txt';
curl_setopt($ch,CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch,CURLOPT_COOKIEFILE, $cookie_file);

Using from the header that is responded back with html source from curl.

curl_setopt($curl_connection, CURLOPT_HEADER, true);
// this is returning the http response header along with html

You'll find the cookies there under the Set-Cookie: header for second example.

By the way, I assume you know how to handle curl. If you don't here are few helps.

Reading Cookie when using Curl in php, how to?

This will do the trick. I run it against Google.com as an example:

<?PHP

// open a site with cookies
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com");
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0');
curl_setopt($ch, CURLOPT_HEADER ,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$content = curl_exec($ch);

// get cookies
$cookies = array();
preg_match_all('/Set-Cookie:(?<cookie>\s{0,}.*)$/im', $content, $cookies);

print_r($cookies['cookie']); // show harvested cookies

// basic parsing of cookie strings (just an example)
$cookieParts = array();
preg_match_all('/Set-Cookie:\s{0,}(?P<name>[^=]*)=(?P<value>[^;]*).*?expires=(?P<expires>[^;]*).*?path=(?P<path>[^;]*).*?domain=(?P<domain>[^\s;]*).*?$/im', $content, $cookieParts);
print_r($cookieParts);

?>

See other examples for how to effectively parse such as string.

PHP - Using cURL to store cookie session into variable / memory

So it turns out I was actually doing this correctly and my assumptions were correct.

  1. To keep the cookie session in a variable (vs. CURLOPT_COOKIEJAR). *Make sure you have CURLOPT_HEADER and CURLINFO_HEADER_OUT enabled.*

  2. CURLOPT_FOLLOWLOCATION must be set to false. Otherwise your cookie won't send correctly (This is where CURLOPT_COOKIEJAR does best).

  3. Use preg_match_all to extract cookies. Then use strpos to find the first occurence of "=". Some sites use encoding and include "="'s which won't work with "explode".

    $data        = curl_exec($curl);
    $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    $header = substr($data, 0, $header_size);

    preg_match_all("/^Set-cookie: (.*?);/ism", $header, $cookies);
    foreach( $cookies[1] as $cookie ){
    $buffer_explode = strpos($cookie, "=");
    $this->cookies[ substr($cookie,0,$buffer_explode) ] = substr($cookie,$buffer_explode+1);
    }
  4. When making your next curl call, re-call the cookie var/object into CURLOPT_COOKIE.

    if( count($this->cookies) > 0 ){
    $cookieBuffer = array();
    foreach( $this->cookies as $k=>$c ) $cookieBuffer[] = "$k=$c";
    curl_setopt($curl, CURLOPT_COOKIE, implode("; ",$cookieBuffer) );
    }

This will allow you to keep the latest variable (i.e. changing sessions) intact.

Hope this helps anyone who bumps into this issue!

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:

# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));

# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

In this case curl will send your defined cookie along with the cookies from the file.

If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).

The utma utmc, utmz are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.

Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt) instead of relative one.

Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.

curl_setopt($ch, CURLOPT_VERBOSE, true);

Set cookie using cURL

Yes, you should use a different file for each client. What you can do is use tempnam() to generate a unique filename for the client, and save this in a session variable, then use it as the cookie jar. The login controller can do this:

session_start();
if (!isset($_SESSION['cookiefile'])) {
$cookiefile = tempnam(".", "cookie");
$_SESSION['cookiefile'] = basename($cookiefile);
}

And then the later page can use

$cookie = "../../km-controllers/" . $_SESSION['cookiefile'];

When the user logs out, you should delete this file and remove the session variable.

There's nothing that will automatically pass the cookies through from the curl session to the client browser or vice versa. If you don't want to save the cookies in a file, you can use curl_getinfo($ch, CURLINFO_COOKIELIST) to get the cookies, but you'll then have to parse the info yourself, and later use CURLOPT_COOKIE to set each cookie when making future calls. The cookie file automates all this.

Full code for login controller.

session_start(); // This needs to be at the very beginning of your script, before anything that produces output
//...
$km_username = filter_var($_POST['userName'], FILTER_SANITIZE_STRING);
$km_user_password = $_POST['userPassword'];

if (!isset($_SESSION['cookiefile'])) {
$cookieFile = tempnam(".", "cookie");
$_SESSION['cookiefile'] = basename($cookiefile);
file_put_contents($cookieFile, "");
}
$cookieFile = $_SESSION['cookiefile'];


$url = 'https://www.apiwebsite.com/api/login.jsp?';

$fields = array(
'userid' => $km_username,
'password' => $km_user_password
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
$content = curl_exec($ch);
curl_close($ch);

And the later interrogator:

session_start(); // at very beginning
// ...

$dates = array(
'd_inizio' => '01/01/2017',
'd_fine' => '31/12/2017'
);

$url = "https://www.apiwebsite.com/api/ricevute.jsp?";
if (!isset($_SESSION['cookiefile'])) {
die("no cookie file");
}
$cookie = "../../km-controllers/" . $_SESSION['cookiefile'];

$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($dates));
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);


Related Topics



Leave a reply



Submit