So you want to open a website with PHP with fopen() or file_get_contents()? But it's taken to long is not available? Well I got this problem with reading my Twitter account that I want to show on the right. Today Twitter has a lot of downtimes so if you check my website, my website taking a long time to load!
UPDATE: Twitter had a DDOS attack that causes the downtime. Well, it's good for testing the code ;)
The only thing you need to do is change the default_socket_timeout ini value like so:
// set timeout for 5 seconds ini_set( 'default_socket_timeout', 5 );
I store all my community feeds into a cache file. So if there's a downtime, it will show the old one stored in the cache. And you don't need to reload the content per every page click. So it's nice to have it stored in cache for like 6 minutes.
function getContents( $url ) { // set the timeout for 3 seconds ini_set( 'default_socket_timeout', 3 ); // store the cachefile into $file $file = md5( $url ); $old = true; if( $f = fopen( "cache/$file", 'r' ) ) { $stat = fstat( $f ); // check if the cache file is NOT older then 360 seconds if( time() - 360 < $stat['mtime'] ) { $old = false; } fclose( $f ); } // if NOT old, return the cache file if( !$old ) { return file_get_contents( "cache/$file" ); } // ...else get the new content, if timeout, return the cache file if( !$con = file_get_contents( $url ) ) { return file_get_contents( "cache/$file" ); } // store the new content in the cache file if( $f = fopen( "cache/$file", 'w' ) ) { fwrite( $f, $con ); fclose( $f ); } // ...and return the new content return $con; } if( $con = getContents( 'http://some.web.page' ) ) { // Woohoo! Do something with it... }