Curl can obtain the cookie Set on the returned page. The principle is the same as that of get_headers. You can retrieve the "Set-Cookie:" Content from the returned header.
Test page/cookie setting page:
Test. php
| The code is as follows: |
Copy code |
<? Php Setcookie ('test', 'SSSS '); Setcookie ('XXX', 'WWW '); |
// Obtain the cookie script
| The code is as follows: |
Copy code |
<? Php $ Url = 'http: // localhost/test. Php '; $ Ch = curl_init ($ url); // Initialization Curl_setopt ($ ch, CURLOPT_HEADER, 1); // output the header file information as a data stream Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); // return the obtained output text stream Curl_setopt ($ ch, CURLOPT_HEADER, 1 ); $ String = curl_exec ($ ch ); Preg_match_all ('/Set-Cookie: stest = (. *)/I', $ string, $ results ); Var_dump ($ results ); |
Get Coke and save it to a file
| The code is as follows: |
Copy code |
$ Url = "http://www.111cn.net /"; $ Ch = curl_init (); Curl_setopt ($ ch, CURLOPT_URL, $ url ); Curl_setopt ($ ch, CURLOPT_HEADER, 0 ); Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true ); Curl_setopt ($ ch, CURLOPT_COOKIEJAR, $ cookie_jar ); $ Content = curl_exec ($ ch ); Curl_close ($ ch ); |
Curl parameters
CURLOPT_COOKIEJAR is used to save cookies to files.
CURLOPT_COOKIEFILE is used to send the stored cookie file
CURLOPT_COOKIE is used to send cookie variables
Because the browser does not save the cookie variable that has not been set to expire after the session ends, no cookie is sent when the browser is closed and the request is sent again.
In curl processing, if it is done once, you only need to CURLOPT_COOKIEJAR.
To perform segment processing, CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE
Do not use CURLOPT_COOKIEJAR. To avoid the impact of new cookie variables