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.

http://www.exmaple.com/old_page http://www.exmaple.com/new_page 
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.


$lines = file('redirects.txt');

foreach ($lines as $line_num => $line) {
	$line = explode(' ', trim($line));
	$headers = @get_headers($line[0], 1);

	if ($headers === FALSE) {
		echo "Line " . ($line_num + 1) . ": Malformed URL found!\n";
	} else if (!isset($headers['Location'])) {
		echo "Line " . ($line_num + 1) . ": " . $line[0] . " does not redirect to " . $line[1] . "\n";
	} else if (isset($headers['Location']) && $headers['Location'] != $line[1]) {
		echo "Line " . ($line_num + 1) . ": " . $line[0] . " redirects to " . $headers['Location'] . " and not " . $line[1] . "\n";

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:

Line 1: http://www.exmaple.com/old_page does not redirect to http://www.exmaple.com/new_page
Line 2: http://www.exmaple.com/nother_old_page does not redirect to http://www.exmaple.com/another_new_page
Finished redirect test.



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


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! :)

Philip Norton

Add new comment

The content of this field is kept private and will not be shown publicly.
3 + 13 =
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.