PHP: Example of usage CURLOPT_HEADERFUNCTION


If you set option CURLINFO_HEADER_OUT to true, you can get request header with function curl_getinfo (see example 2)

<?php
$headers = array();
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://tutorialspots.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_HEADERFUNCTION,'header_callback');
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$content = curl_exec($ch);
curl_close($ch);

function header_callback($ch, $header_line)
{ 
    global $headers;
    $headers[] = $header_line;
    return strlen($header_line);
}

var_dump($headers);

CURLOPT_HEADERFUNCTION: A callback accepting two parameters. The first is the cURL resource, the second is a string with the header data to be written. The header data must be written by this callback. Return the number of bytes written.

Result:

array(13) {
  [0]=>
  string(17) "HTTP/1.1 200 OK
"
  [1]=>
  string(37) "Date: Wed, 10 May 2017 04:51:13 GMT
"
  [2]=>
  string(40) "Content-Type: text/html; charset=UTF-8
"
  [3]=>
  string(28) "Transfer-Encoding: chunked
"
  [4]=>
  string(24) "Connection: keep-alive
"
  [5]=>
  string(23) "Vary: Accept-Encoding
"
  [6]=>
  string(49) "X-Pingback: http://tutorialspots.com/xmlrpc.php
"
  [7]=>
  string(50) "Link: <http://tutorialspots.com/>; rel=shortlink
"
  [8]=>
  string(15) "Server: Nginx
"
  [9]=>
  string(22) "X-Powered-By: VPSSIM
"
  [10]=>
  string(33) "X-Content-Type-Options: nosniff
"
  [11]=>
  string(33) "X-XSS-Protection: 1; mode=block
"
  [12]=>
  string(2) "
"
}

Example 2: Example with function curl_getinfo

...
$info = curl_getinfo($ch);
curl_close($ch);

var_dump($info);

Result:

array(27) {
  ["url"]=>
  string(25) "http://tutorialspots.com/"
  ["content_type"]=>
  string(24) "text/html; charset=UTF-8"
  ["http_code"]=>
  int(200)
  ["header_size"]=>
  int(373)
  ["request_size"]=>
  int(56)
  ["filetime"]=>
  int(-1)
  ["ssl_verify_result"]=>
  int(0)
  ["redirect_count"]=>
  int(0)
  ["total_time"]=>
  float(2.294)
  ["namelookup_time"]=>
  float(0)
  ["connect_time"]=>
  float(0.25)
  ["pretransfer_time"]=>
  float(0.25)
  ["size_upload"]=>
  float(0)
  ["size_download"]=>
  float(120792)
  ["speed_download"]=>
  float(52655)
  ["speed_upload"]=>
  float(0)
  ["download_content_length"]=>
  float(-1)
  ["upload_content_length"]=>
  float(0)
  ["starttransfer_time"]=>
  float(1.077)
  ["redirect_time"]=>
  float(0)
  ["redirect_url"]=>
  string(0) ""
  ["primary_ip"]=>
  string(14) "172.82.140.120"
  ["certinfo"]=>
  array(0) {
  }
  ["primary_port"]=>
  int(80)
  ["local_ip"]=>
  string(11) "192.168.1.4"
  ["local_port"]=>
  int(61614)
  ["request_header"]=>
  string(56) "GET / HTTP/1.1
Host: tutorialspots.com
Accept: */*

"
}