轉自 https://blog.devgenius.io/how-to-get-the-response-headers-with-curl-in-php-2173b10d4fc5
--
How To Get the Response Headers with cURL in PHP
There is no built-in solution for this, but we can easily create our own
Many public APIs are using custom headers to convey some additional data like rate limits or access restrictions to the user. When using XMLHttpRequests
in JavaScript you can easily get them with the getAllResponseHeaders()
or getResponseHeader(headerName)
functions. A few days ago, I was using a new API with custom headers with cURL in PHP and I thought there would be an easy built-in function for this as well.
However, after a quick search, I realized that there was no built-in solution for this. Luckily, with a bit more work, it’s possible to get the response headers anyway.
Response Headers in cURL
There is a simple solution built into cURL if you are only interested in the response headers and not the content of the body. By setting the CURLOPT_HEADER
and CURLOPT_NOBODY
options to true, the result of curl_exec()
will only contain the headers. This is useful when you only need the headers, but most of the time, we need the content of the request too.
The solution to this lies in the CURLOPT_HEADER
option as well. Setting it to true will include the headers in the output of curl_exec()
. However, without the CURLOPT_NOBODY
option, we now have an output that contains the headers and the body of the request and we need to split them apart. This can be done with the CURLINFO_HEADER_SIZE
parameter in the curl_getinfo()
function, which will tell us the length of the headers and we can easily use that value to create two substrings for the headers and the body.
At this point, we have a long string with all headers which isn’t particularly user-friendly. So let’s implement a function to create a nice associative array with the header names as keys and their values as values:
A Complete Example
Let’s start by creating a quick example API and set some custom headers:
Now, let's do a cURL request to our test API and use the function from before to get out custom headers and the body content at the same time:
If we look at the output of the script we can see that we get the values from our custom headers and still have access to the values in the body:
CUSTOM_HEADER: Hello World
API_REQUEST_COUNTER: 42
API_REQUEST_LIMIT: 69
Body: {"result":true,"someValue":420}
While there is no built-in solution to retrieve response header values in cURL in PHP, it’s easily possible to create our own custom function for it. By setting a special option the headers are included in the output and we can split them from the content of the request. We can then turn them into a user-friendly associative array and easily access their values. If you are using any APIs with custom headers using cURL in PHP, this is a very useful tool to have.
--