Monday, May 30, 2011

Safe file_get_contents

If we want to get file from remote location and link is valid but file does not exist, we get connection refused error and php returns critical error and kills the script (at least in my version of php). Using @ won't help. For accessing external locations I use this method:


static public function safe_url_get_contents
($url,$include_path = false,$context = null,
$start = -1,$max_length = null)
   {
      $strItem = FALSE;
      if (self::checkUrl($url))
      {
         if (!is_numeric($max_length))
         {
            $strItem = file_get_contents($url,$include_path,$context,$start);
         }
         else 
         {
            $strItem = file_get_contents($url,$include_path,$context, $start, $max_length);
         }
         
       }
       
       return $strItem;
   }

   static public function checkUrl($url)
   {
      @$headers = get_headers($url);
      if (preg_match('/^HTTP\/\d\.\d\s+(200|301|302)/', $headers[0]))
      {
         return true;
      }
      else
         return false;
   }

Although it introduces the overhead of checking the headers I believe it to be a small price to pay, when alternative is PHP to fail.

Post a Comment