Home >Backend Development >PHP Tutorial >How to Efficiently Retrieve Both Headers and Body from a PHP cURL Response?
Retrieving Response Headers and Body in PHP cURL
While using PHP cURL, it is possible to retrieve both response headers and the body in a single request. One common approach involves setting CURLOPT_HEADER to true, which returns the body along with headers. However, parsing this combined response to extract the body requires additional processing.
An alternative method suggested by the PHP documentation comments offers a more structured approach:
Code:
$ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); // ... $response = curl_exec($ch); // Get header and body after execution: $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($response, 0, $header_size); $body = substr($response, $header_size);
This approach provides cleaner access to the header and body components of the response.
Caution:
It's important to note that this method may not be reliable in all scenarios, particularly when using proxy servers or handling certain types of redirects. For enhanced reliability, consider @Geoffrey's alternative solution provided in the comment section, which addresses these edge cases.
The above is the detailed content of How to Efficiently Retrieve Both Headers and Body from a PHP cURL Response?. For more information, please follow other related articles on the PHP Chinese website!