Use curl in php to obtain the cookie of the returned page

Source: Internet
Author: User

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

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.