简体   繁体   中英

Using cookie in curl call with PHP

I need to fetch some data from external site. To do this I need to load a site that creates some cookie and gives a simple math calculation to generate new link. This part is easy:

$cr = curl_init($url);
curl_setopt($cr, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cr, CURLOPT_COOKIEJAR, 'cookie.txt');
$html = curl_exec($cr);
curl_close($cr);

After those calls I have cookies stored in cookie.txt:

# Netscape HTTP Cookie File
# http://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

domain   FALSE   /       FALSE   0       PHPSESSID       o89t753egbp9pq9084n38eg2m1

Now, the question is: how can I load this cookie to use it in my next call to some other site (in the same domain ofcourse)?

You can use

curl_setopt($cr, CURLOPT_COOKIEFILE, 'cookie.txt'); 
curl_setopt($cr, CURLOPT_COOKIEJAR, 'cookie.txt'); 

in both requests.

A cookie is a header, then you can simply use the command setcookie($name,$value), or if you prefer, using the header php call, using Cookie for header name. Remember, you don't have to send output to the client before the setcookie command.

You have to read file and split it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM