PHP-alternativa funkciji file get contents

Pošto je isključena funkcionalnost allow_url_fopen(), nije moguće vršiti priključivanje fajlova sa druguh lokacija pomoću funkcije file_get_contents().

Ako imate sajt na UNIX serveru onda možete koristiti cURL kako je opisano ovde. Za korisnike na Windows serveru postoji alternativno rešenje koje smo razvili:

function file_get_url_contents($url) {
   if (preg_match('/^([a-z]+):\/\/([a-z0-9-.]+)(\/.*$)/i', 
     $url, $matches)) {
      $protocol = strtolower($matches[1]);
      $host = $matches[2];
      $path = $matches[3];
   } else {
      // Bad url-format
      return FALSE;
   }

   if ($protocol == "http") {
      $socket = fsockopen($host, 80);
   } else {
      // Bad protocol
      return FALSE;
   }

   if (!$socket) {
      // Error creating socket
      return FALSE;
   }

   $request = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";
   $len_written = fwrite($socket, $request);

   if ($len_written === FALSE || $len_written != strlen($request)) {
      // Error sending request
      return FALSE;
   }

   $response = "";
   while (!feof($socket) &&
         ($buf = fread($socket, 4096)) !== FALSE) {
      $response .= $buf;
   }

   if ($buf === FALSE) {
      // Error reading response
      return FALSE;
   }

   $end_of_header = strpos($response, "\r\n\r\n");
   return substr($response, $end_of_header + 4);
}

Poziv funcije se vrši na sledeći način (zamenite http://www.loopia.se/ sa adresom koju želite da download-ujete:

$url = "http://www.loopia.se/";
$res = file_get_url_contents($url);
if ($res === FALSE) {
   echo "Error fetching $url";
} else {
   echo $res;
}
Was this article helpful?

Related Articles