

Using this method, we can return both the body and header part of the response. Next, we will need to cut out the headers.

#PHP CURL RESPONSE HEADERS FULL#
However, we can still cut them from the full response. Doing this will include the headers in the response downloaded by cURL. There is no build-in way to only return the response headers using cURL in PHP. To do this, we first determine the size of the response header, and then simply cut it from the response using the substr() function.įirst, we set the CURLOPT_HEADER option true. However, we can still "cut" them from the full response. There is no build-in way to only return the response headers using cURL in PHP. Here is a tested working code: function HandleHeaderLine( $curl, $header_line ) elseif (substr($header, 0, 8) = 'HTTP/1.// Convert the $headers string to an indexed array $headers_indexed_arr = explode ( " \r\n ", $headers ) // Define as array before using in loop $headers_arr = array () // Remember the status message in a separate variable $status_message = array_shift ( $headers_indexed_arr ) // Create an associative array containing the response headers foreach ( $headers_indexed_arr as $value ) // Show that it works header ( 'content-type: text/plain charset=utf-8' ) print_r ( $headers_arr ) exit () Retrieving the response headers Your callback function then can do anything with it (and must return the number of bytes of the given line). Curl will pass the header (and the header only!) to this callback function, line-by-line (so the function will be called for each header line, starting from the top of the header section). The value of this option must be the name of a callback function. $headers))] = trim($header) Ĭurl has a built in option for this, called CURLOPT_HEADERFUNCTION. If (count($header) < 2) // ignore invalid headers this function is called by curl for each header received

This complies with RFC822 and RFC2616, please do not make use of the mb_ (and similar) string functions, it is a not only incorrect but even a security issue RFC-7230! $ch = curl_init() Ĭurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1) This version will retain duplicated headers In this Curl Request With Bearer Token Authorization Header example, we send a GET request to the ReqBin echo URL. It also converts all headers to lowercase for consistent handling across servers and HTTP versions. To send a Curl POST request, you need to pass the POST data with the -d command line option, and the authorization header and bearer token are passed with the -H command line option. Here is a very clean method of performing this using PHP closures. The most correct method is using CURLOPT_HEADERFUNCTION.
#PHP CURL RESPONSE HEADERS CODE#
Splitting on \r\n\r\n is not reliable when CURLOPT_FOLLOWLOCATION is on or when the server responds with a 100 code RFC-7231, MDN.Many of the other solutions offered this thread are not doing this correctly.
