I was looking for a quick way to detect any 3XX redirections, therefore I came up with this small routine.

The web is getting more and more interweaved, and websites often need to consume other content. Or sometimes need to convert an older static website to Drupal using a parser. In both cases, we might need to implement some strategy regarding redirects, like for example placing a is_redirect on the URL in a cron, and sending the result to watchdog

// Detect redirect function is_redirect($url) {     # 1. Prevent redirects   $opts = array('http' =>     array('max_redirects'=>1, 'ignore_errors'=>1)   );   stream_context_get_default($opts);     # 2. Get headers (does not take context argument like file_get_contents)   $headers = get_headers($url,true);     # 3. Restore stream settings   $opts = array('http' =>     array('max_redirects'=>20, 'ignore_errors'=>0)   );   stream_context_get_default($opts);     # 4. Extract http request status code   $status = $headers[0];   list($protocol,$code,$message) = split(' ', $status,3);     # 5. Detect redirect   return ($code>=300 && $code<400); } // Find location of redirect function loc_redirect($url) {    # 1. Prevent redirects  $opts = array('http' =>   array('max_redirects'=>1,'ignore_errors'=>1)  );  stream_context_get_default($opts);    # 2. Get headers (does not take context argument like file_get_contents)  $headers = get_headers($url,true);    # 3. Restore stream settings  $opts = array('http' =>   array('max_redirects'=>20,'ignore_errors'=>0)  );  stream_context_get_default($opts);    # 4. Extract http request status code  $status = $headers[0];  list($protocol,$code,$message) = split(' ',$status,3);    # 5. Find redirect  return ($code>=300 && $code<400) ? $headers['Location'] : FALSE; }

This is not the most advanced hint, but It might save some time to someone looking for a quick copy-paste solution!

Read Next
Appnovation Blog Default Header

Rounded Corners With jQuery

09 July, 2010|2 min