miguel.nz

Checking if a website URL and its redirections are all working

December 21, 2023   |   1 minute read.

I have been working on a new website lately and I wanted to check whether the URL have been properly migrated. Some URLs have changed and others have been redirected to a new domain.

Additional to my .htaccess I wanted to create a small script to check whether my redirections were working or not. Here is the code:

$color_red = "\033[0;31m";
$color_green = "\033[0;32m";
$color_reset = "\033[0m";

// Sample array of addresses
$allowedAddresses = [
  'http://example.com'
];

foreach($allowedAddresses as $item) {
  $final_url = get_final_url($item);
  $response_code = get_response_code($final_url);
  $output_color = ($response_code == '200') ? $color_green : $color_red;

  echo  $output_color . " " . $response_code . " -- " . $item . " | " . $final_url . " " . $color_reset . "\n";
}

function get_final_url($url) {
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_HEADER, true);
  $response = curl_exec($ch);
  $final_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  curl_close($ch);

  return $final_url;
}

function get_response_code($theURL) {
  $headers = get_headers($theURL);
  return substr($headers[0], 9, 3);
}

This PHP script is meant to run on the terminal via

$ php test-redirection-urls.php