abhi_madhani

PHP URL Recursive Redirect Checker

Nov 3rd, 2014
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.59 KB | None | 0 0
  1. <?php
  2.  
  3.     function get_curl_data($url, &$curl_data = array(), $redirect_count = 0) {
  4.  
  5.         $url = url_path_encode(trim($url));
  6.        
  7.         $timeout = 500;
  8.         $conn_timeout = 500;
  9.         $max_redirect = 10;
  10.  
  11.         $ch = curl_init();
  12.         curl_setopt($ch, CURLOPT_URL, $url);
  13.         curl_setopt($ch, CURLOPT_HEADER, true);
  14.         curl_setopt($ch, CURLOPT_NOBODY, TRUE);
  15.         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
  16.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  17.         curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64; rv:21.0) Gecko/20100101 Firefox/21.0");
  18.         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  19.         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $conn_timeout);
  20.         $data = curl_exec($ch);
  21.  
  22.         $curl_data[$url]['header'] = curl_getinfo($ch);
  23.         curl_close($ch);
  24.  
  25.         // Check if Redirection codes between 301 - 308 is returned
  26.         if ( substr($curl_data[$url]['header']['http_code'], 0, 2) === '30' ) {
  27.  
  28.             $curl_data[$url]['redirect_count'] = ++$redirect_count;
  29.             $redirect_url = &$curl_data[$url]['header']['redirect_url'];
  30.  
  31.             // Check for max redirects
  32.             if ($redirect_count == $max_redirect) {
  33.                 $redirect_url = "{$redirect_url} ... [max redirection reached]";
  34.                 return $curl_data;
  35.             }
  36.  
  37.             // Check for infinite loop
  38.             if (isset($curl_data[$redirect_url])) {
  39.                 $redirect_url = "{$redirect_url} ... [infinite loop detected]";
  40.                 return $curl_data;
  41.             }
  42.  
  43.             $curl_data = get_curl_data($redirect_url, $curl_data, $redirect_count);
  44.         }
  45.  
  46.         return $curl_data;
  47.     }
  48.  
  49.     // Check url recursive redirects
  50.     $url = 'http://www.domain.com/redirect1';
  51.     $curl_data = get_curl_data($url);
  52.  
  53. ?>
Advertisement
Add Comment
Please, Sign In to add comment