note 48996 deleted from function.file by curt

From: Date: Tue, 14 Nov 2006 02:25:27 +0000
Subject: note 48996 deleted from function.file by curt
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-119698@lists.php.net to get a copy of this message
Note Submitter: Jason dot haymer at Haymer dot co dot uk ---- Beware of using file() to call a URL from a remote server on a live Web site, as there is no way to set a maximum connection time. To exemplify this I cite the circumstance of a Web site which receives content from a remote server in the form of an XML feed. If the remote server does not respond, the Web page will hang and if this is a regular occurance, the parts of the Web site which use the feed may often prove inaccessible to search engine robots, possibly resulting in their removal from the search engine indices. Here is an alternative function which like file() can be used to retrieve a remote feed, but which imposes a maximum connection time, after which the page will be displayed without the feed. <? function fetchUrlWithoutHanging($url) { // Set maximum number of seconds (can have floating-point) to wait for feed before displaying page without feed $numberOfSeconds=4; // Suppress error reporting so Web site visitors are unaware if the feed fails error_reporting(0); // Extract resource path and domain from URL ready for fsockopen $url = str_replace("http://","",$url); $urlComponents = explode("/",$url); $domain = $urlComponents[0]; $resourcePath = str_replace($domain,"",$url); // Establish a connection $socketConnection = fsockopen($domain, 80, $errno, $errstr, $numberOfSeconds); if (!$socketConnection) { // You may wish to remove the following debugging line on a live Web site print("<!-- Network error: $errstr ($errno) -->"); } // end if else { $xml = ''; fputs($socketConnection, "GET /$resourcePath HTTP/1.0\r\nHost: $domain\r\n\r\n"); // Loop until end of file while (!feof($socketConnection)) { $xml .= fgets($socketConnection, 128); } // end while fclose ($socketConnection); } // end else return($xml); } // end function ?>

« previous php.notes (#119698) next »