PHP uses curl not rely on cookiejar to get cookies

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.

?

1

2

3//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? Suspense, directly on the code:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18//Initialization Curl

$ch = Curl_init ();

curl_setopt ($ch, Curlopt_url, $url);

Get header information

curl_setopt ($ch, Curlopt_header, 1);

Returns the raw (RAW) output

curl_setopt ($ch, Curlopt_returntransfer, true);

Execute and get the return result

$content = curl_exec ($ch);

Close Curl

Curl_close ($ch);

Parsing HTTP data streams

List ($header, $body) = Explode ("Rnrn", $content);

Parsing cookies

Preg_match ("/set-cookie: ([^rn]*)/I", $header, $matches);

It can be used directly after submitting with curl.

curl_setopt ($ch, Curlopt_cookie, $cookie);

$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.