Home > Article > Backend Development > How to obtain COOKIE in php using CURL without relying on COOKIEJAR_PHP Tutorial
This article describes the example of how PHP uses CURL to obtain COOKIE without relying on COOKIEJAR. Share it with everyone for your reference. The specific analysis is as follows:
The CURL class in PHP is a very awesome tool class. I won’t go into details about how awesome it is.
For COOKIE, the CURL class also has very good support, but it is not flexible enough and cannot be obtained through ready-made methods using variables. It must be implemented through the following methods.
?
1
2
3// Save COOKIE to cookie.txt
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
First save the COOKIE file, and then read the file when calling. This means two IO operations. Needless to say, everyone knows how efficient it is.
So is there a way to bypass writing and reading files? Don’t be too pretentious, just go to the code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18//Initialize CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Get header information
curl_setopt($ch, CURLOPT_HEADER, 1);
// Return raw (Raw) output
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute and get the return result
$content = curl_exec($ch);
// Close CURL
curl_close($ch);
// Parse HTTP data stream
list($header, $body) = explode("rnrn", $content);
// Parse COOKIE
preg_match("/set-cookie:([^rn]*)/i", $header, $matches);
// You can use it directly when submitting with CURL later
// curl_setopt($ch, CURLOPT_COOKIE, $cookie);
$cookie = $matches[1];
I hope this article will be helpful to everyone’s PHP programming design.