乐闻世界logo
搜索文章和话题

How to get the cookies from a php curl into a variable

1个答案

1

To retrieve cookies from PHP cURL and store them in variables, follow these steps. This can be achieved by configuring cURL options to save cookie information from the response into a variable. I will demonstrate the process using a specific example.

Step 1: Initialize the cURL Session

First, initialize a cURL session using the curl_init() function.

php
$curl = curl_init();

Step 2: Set cURL Options

Next, configure the necessary options for this cURL session. Importantly, set the URL and enable cookie handling.

php
curl_setopt($curl, CURLOPT_URL, "http://example.com"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, true); // When enabled, it outputs header information as a data stream. curl_setopt($curl, CURLOPT_COOKIEJAR, '/tmp/cookies.txt'); // Specify a file to save cookies. curl_setopt($curl, CURLOPT_COOKIEFILE, '/tmp/cookies.txt'); // Read cookies from this file.

Step 3: Execute the cURL Request and Retrieve the Response

Execute the cURL request to obtain the response containing headers.

php
$response = curl_exec($curl);

Step 4: Parse Cookies from the Response

Since CURLOPT_HEADER is set to true, the response includes HTTP headers. Parse the cookies from this information.

php
// Match cookies and store them in an array preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $response, $matches); $cookies = array(); foreach($matches[1] as $item) { parse_str($item, $cookie); $cookies = array_merge($cookies, $cookie); }

Step 5: Close the cURL Session

Finally, close the cURL session to free resources.

php
curl_close($curl);

Step 6: Use the Cookies

The $cookies array now contains the parsed cookies from the response, which you can use as needed.

php
print_r($cookies);

Summary

These steps demonstrate how to extract cookies from PHP cURL responses and store them in variables. This approach is valuable for scenarios involving web request handling, such as login verification and session management.

2024年8月12日 11:30 回复

你的答案