Extracting Headers and Body from cURL Requests in PHP
The PHP cURL library provides a convenient way to send HTTP requests. By default, cURL fetches only the response body. However, you may encounter situations where you need to access both the headers and body in a single request, without issuing a separate HEAD request.
Solution: Separating Headers and Body
To retrieve both headers and body in a single cURL request, you can utilize the following steps:
Execute the cURL request with curl_exec() with the following options:
Example Code:
$ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); // ... $response = curl_exec($ch); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($response, 0, $header_size); $body = substr($response, $header_size);
Note: Be aware that this method may not be reliable in all cases, particularly when dealing with proxy servers or certain types of redirects.
The above is the detailed content of How Can I Extract Both Headers and Body from a cURL Request in PHP?. For more information, please follow other related articles on the PHP Chinese website!