This article describes the example of php using CURL without relying on COOKIEJAR to obtain COOKIE. 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 the variable method through ready-made methods. It must be achieved through the following method.
// 把COOKIE保存至cookie.txt curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
Save the COOKIE file first, 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 upload the code:
// 初始化CURL $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // 获取头部信息 curl_setopt($ch, CURLOPT_HEADER, 1); // 返回原生的(Raw)输出 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 执行并获取返回结果 $content = curl_exec($ch); // 关闭CURL curl_close($ch); // 解析HTTP数据流 list($header, $body) = explode("\r\n\r\n", $content); // 解析COOKIE preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches); // 后面用CURL提交的时候可以直接使用 // curl_setopt($ch, CURLOPT_COOKIE, $cookie); $cookie = $matches[1];
I hope this article will be helpful to everyone’s PHP programming design.