Use PHP Curl To Get Header Data From A Web Page

// Initialise curl.
$ch = curl_init();

$url = 'https://www.hashbangcode.com/';

// Setup curl to fetch the headers.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36');
curl_setopt($ch, CURLOPT_FILETIME, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);

// Execute the request and return the header data as a string.
$headers = curl_exec($ch);

// Extract information about the request, including the http response code.
$info = curl_getinfo($ch);

curl_close($ch);

if ($info['http_code'] == '200') {
   echo 'ok!' . PHP_EOL;
}

// Extract header data into an array.
$headerData = [];

$headers = explode(PHP_EOL, $headers);
foreach ($headers as $row) {
  $parts = explode(':', $row);
  if (count($parts) === 2) {
    $headerData[trim($parts[0])] = trim($parts[1]);
  }
}

// Print header data.
print_r($headerData);

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
4 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.