Friday, 10 August 2018

Testing 301 Redirects Using PHP

I'm always writing bits of script to test things out and I thought that I would start making a record of them in case I need them in the future. This is a little script that will loop through the contents of a text file and validate that a bunch of 301 redirects point to the place they are meant to point to. This script assumes that the redirects are already in place on the server, but this is what I was testing. Here the format of the redirects text file.
  1. http://www.exmaple.com/old_page http://www.exmaple.com/new_page
  2. http://www.exmaple.com/nother_old_page http://www.exmaple.com/another_new_page
The script below loads in this file and loops through it using the PHP function get_headers() to test that the first URL redirects to the second. If any problems are found then the line number and the problem is reported on.
  1. <?php $lines = file('redirects.txt');
  2.  
  3. foreach ($lines as $line_num =?> $line) {
  4. $line = explode(' ', trim($line));
  5. $headers = @get_headers($line[0], 1);
  6.  
  7. if ($headers === FALSE) {
  8. echo "Line " . ($line_num + 1) . ": Malformed URL found!\n";
  9. } else if (!isset($headers['Location'])) {
  10. echo "Line " . ($line_num + 1) . ": " . $line[0] . " does not redirect to " . $line[1] . "\n";
  11. } else if (isset($headers['Location']) && $headers['Location'] != $line[1]) {
  12. echo "Line " . ($line_num + 1) . ": " . $line[0] . " redirects to " . $headers['Location'] . " and not " . $line[1] . "\n";
  13. }
  14. }
  15.  
  16. echo "Finished redirect test.\n";
Using the above example is a good idea here as it demonstrates what happens if a problem is found. Here is the output:
  1. Line 1: http://www.exmaple.com/old_page does not redirect to http://www.exmaple.com/new_page
  2. Line 2: http://www.exmaple.com/nother_old_page does not redirect to http://www.exmaple.com/another_new_page
  3. Finished redirect test.

0 comments:

Post a Comment