Home > Backend Development > PHP Tutorial > How to Extract Cookies from a PHP cURL Response Using Regular Expressions?

How to Extract Cookies from a PHP cURL Response Using Regular Expressions?

Linda Hamilton
Release: 2024-12-26 01:39:09
Original
352 people have browsed it

How to Extract Cookies from a PHP cURL Response Using Regular Expressions?

Extracting Cookies from a PHP cURL Response

Retrieving cookies embedded in HTTP headers can be essential for parsing responses from non-standard communication protocols. To simplify this task, avoid unnecessary file write operations, and potentially save ample time, consider the following solution using PHP's cURL extension:

// Initialize cURL
$ch = curl_init('http://www.google.com/');

// Enable response caching and header retrieval
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);

// Execute cURL request
$result = curl_exec($ch);

// Extract cookies from header using regular expression (multi-cookie support)
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);
}

// Display the extracted cookies as an array
var_dump($cookies);
Copy after login

This solution effectively extracts cookies from a cURL response using regular expressions and stores them in an associative array. By leveraging PHP's built-in cookie handling capabilities, you can avoid writing to a file and simplify the process of parsing cookies from custom protocols.

The above is the detailed content of How to Extract Cookies from a PHP cURL Response Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template