Save cookies from one request and use another next Curl

Asked

Viewed 934 times

0

I am trying to log into a website and save cookies to have access to other pages, I found the option 'CURLOPT_COOKIEJAR' that saves cookies in a NETSCAPE file, the doubt is how would be made a second request to another URL using other POST parameters, using the same $ch, how best to proceed?

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://site.com.br');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'login=usuario&senha=123456');
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . '/cookies.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$content = curl_exec($ch);


curl_close($ch);

1 answer

1

Use the CURLOPT_COOKIEFILE "pointed" to the same file.

//...
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . '/cookies.txt');
//...

The cookies.txt will have cookies written by JAR and will be read by FILE.

  • Then I repeat the same arguments used in the previous request? this will overwrite?

  • The CURLOPT_COOKIEFILEjust reads, it can use the file endlessly. Already the CURLOPT_COOKIEJAR just type. If you use CURLOPT_COOKIEJAR for the same file it will overwrite, if you intend to "log in with several different accounts" then each one should use a file for each one.

  • This part I understood cool, I say how to proceed after saving the cookie and using the CURLOPT_COOKIEFILE, I should use the same arguments for a new request before curl_close, right?

  • This depends on the request you want to make, whether it is identical to the previous one or not. Other parameters should be included, inclusion of JAR, for example, is optional.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.