CURL PHP example demonstration
Sunday, April 19, 2009 23:54PHP has a very powerful library of calls that are specifically designed to safely fetch data from remote servers and sites. It is called CURL or C URL. Here is the example:
<?php $curl_handle=curl_init(); curl_setopt($curl_handle,CURLOPT_URL,'http://www.myexample.com'); curl_exec($curl_handle); curl_close($curl_handle); ?>
It’s finished, and if you really wanted, the last curl_close() step is optional.
Keep in mind, you’re still subject to the javascript and cookie from the remote site, but that involves more work than you probably want to do. If you do want to do it, I will suggest Regular Expressions and preg_replace()
Let’s say that myexample.com isn’t really that reliable. It bugs you that whenever they’re down, your page takes 30 seconds to load. Well, there’s a solution to that:
<?php $curl_handle=curl_init(); curl_setopt($curl_handle,CURLOPT_URL,'http://www.myexample.com'); curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2); curl_exec($curl_handle); curl_close($curl_handle); ?>
What that says is to time out after only two seconds. Heck, you may want to set it to 1 second to make your page load even zippier. (Be careful not to set it to zero (zed to you outside of the US). That tells curl to never time out.)
But what if you also want to display a message!
<?php
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://www.myexample.com');
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
if (empty($buffer)){
print "Ooops, www.myexample.com is not accessible.<p>";
}else{
print $buffer;
}
?>


