Last active
August 29, 2015 14:19
-
-
Save nvahalik/d07a27666b0ac0112e01 to your computer and use it in GitHub Desktop.
Quick redirect checker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This file provides a quick-n-dirty method for testing redirects. | |
* | |
* Just edit the $tests array and run from the CLI. | |
* | |
* If you are having problems, try making sure your DNS server is set to | |
* something that isn't dnsmasq as I had problems with with it while | |
* running this for a website in development. | |
*/ | |
/** | |
* This is an array of arrays, where each subarray has the following keys: | |
* - test_uri: The URI to test. | |
* - status: The expected status code. | |
* - location: The expected redirect location for the request. | |
*/ | |
$tests = array( | |
// Redirect to the naked version of a URL. | |
array('test_uri' => 'http://www.mywebsite.com/', 'status' => '301', 'location' => 'http://mywebsite.com/'), | |
// Make sure this doesn't redirect. | |
array('test_uri' => 'http://mywebsite.com/', 'status' => '200', 'location' => ''), | |
); | |
/** | |
* Returns the status code and redirect location for a given URL. | |
* | |
* @param $url | |
* The URL to test. | |
* @return array | |
* An array containing the following keys: | |
* - status: The HTTP status code. | |
* - location: The value of the Location header. | |
*/ | |
function do_http_request($url) { | |
$headers = @get_headers($url, 1); | |
if (is_array($headers[0])) $headers[0] = $headers[0][0]; | |
if (is_array($headers['Location'])) $headers['Location'] = $headers['Location'][0]; | |
$statuscode = explode(' ', $headers[0])[1]; | |
return array('status' => $statuscode, 'location' => !empty($headers['Location']) ? $headers['Location'] : ''); | |
} | |
/** | |
* Runs the tests over the test array and outputs the results to stdout. | |
* | |
* @param $tests Array Aerray of test arrays. (See above.) | |
*/ | |
function test_redirects($tests) { | |
foreach ($tests as $test) { | |
$status = 'FAIL'; | |
$info = do_http_request($test['test_uri']); | |
if ($info['status'] == $test['status'] && $info['location'] == $test['location']) { | |
$status = 'OK!'; | |
} | |
printf("%4s (%-45s) Got: %3d %-45s | |
Expected: %3d %-45s\n", | |
$status, $test['test_uri'], $info['status'], $info['location'], $test['status'], $test['location'] | |
); | |
} | |
} | |
// Do them! | |
test_redirects($tests); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment