PHP uses curl not rely on Cookiejar to get cookies _php tips

Source: Internet
Author: User
Tags curl

The example in this article describes how PHP uses curl to get cookies without relying on cookiejar. Share to everyone for your reference. The specific analysis is as follows:

PHP Curl class is a very good tool class, the specific how to not verbose.

It also has good support for the Cookie,curl class, but it is not flexible enough to be obtained by means of a variable method, and is implemented in the following ways.

Save cookies to Cookie.txt 
curl_setopt ($ch, Curlopt_cookiefile, ' cookie.txt '); 
curl_setopt ($ch, Curlopt_cookiejar, ' cookie.txt '); 

Save the cookie file for the first time, and read the file when it is called, which means two IO operations and how efficient it is, needless to say, everyone knows.
So is there a way to bypass the read file? Not suspense, directly on the code:

Initialization of curl 
$ch = Curl_init (); 
curl_setopt ($ch, Curlopt_url, $url); 
information 
curl_setopt ($ch, Curlopt_header, 1); 
Returns the raw (raw) output 
curl_setopt ($ch, Curlopt_returntransfer, true); 
Executes and obtains the return result 
$content = curl_exec ($ch); 
Closure of Curl 
curl_close ($ch); 
Parsing HTTP Data Flow 
list ($header, $body) = Explode ("\r\n\r\n", $content); 
Parse Cookie 
preg_match ("/set\-cookie: ([^\r\n]*)/I", $header, $matches); 
The latter can be directly used 
//curl_setopt ($ch, Curlopt_cookie, $cookie) when submitted with curl; 
$cookie = $matches [1]; 

I hope this article will help you with your PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.