Testing 301 Redirects Using PHP

3rd January 2012 - 2 minutes read time

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
  2.  
  3. $lines = file('redirects.txt');
  4.  
  5. foreach ($lines as $line_num => $line) {
  6. $line = explode(' ', trim($line));
  7. $headers = @get_headers($line[0], 1);
  8.  
  9. if ($headers === FALSE) {
  10. echo "Line " . ($line_num + 1) . ": Malformed URL found!\n";
  11. } else if (!isset($headers['Location'])) {
  12. echo "Line " . ($line_num + 1) . ": " . $line[0] . " does not redirect to " . $line[1] . "\n";
  13. } else if (isset($headers['Location']) && $headers['Location'] != $line[1]) {
  14. echo "Line " . ($line_num + 1) . ": " . $line[0] . " redirects to " . $headers['Location'] . " and not " . $line[1] . "\n";
  15. }
  16. }
  17.  
  18. 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.

 

Comments

Permalink

Shouldn't this rather be an functional phpunit test? I would suggest so, even the heading starts with Testing

Tjorriemorrie (Wed, 01/04/2012 - 04:28)

Permalink

It didn't occur to me at the time to use phpunit to do this, but now that you mention it I can't think of a good reason why it shouldn't be. Thanks for the suggestion! :)

Add new comment

The content of this field is kept private and will not be shown publicly.