Alternative to file_get_contents() using cUrl

Alternative to file_get_contents() using cUrl

转载:http://www.php2k.com/blog/php/advanced-php/alternative-to-file_get_contents-using-curl/

The function file_get_contents() reads a file into a string. Using the function doesnt always work or sometimes uses more server memory. Another way of grabbing content from a url is using cUrl. cUrl allows you to grab/retrieve content from another server/url.

I have written a simple function which will retrieve content from the given url using cUrl.

<?php

function getPage($url, $referer, $timeout, $header){
if(!isset($timeout))
$timeout=30;
$curl = curl_init();
if(strstr($referer,"://")){
curl_setopt ($curl, CURLOPT_REFERER, $referer);
}
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt ($curl, CURLOPT_USERAGENT, sprintf("Mozilla/%d.0",rand(4,5)));
curl_setopt ($curl, CURLOPT_HEADER, (int)$header);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
$html = curl_exec ($curl);
curl_close ($curl);
return $html;
}

?>

To use the function you will need to define 3 things.

“url” - The url you want to retreve

“refer” - Where would you like the website to think you came from, i.e. http://google.com

“timeout” - How long before you want your server to quit if the site doesnt respond. (30 seconds should be fine).

Now you understand the 3 main points you need to define, i will show you how to use the function.

<?php

getPage(’http://YourDomain.Com’, ‘http://google.com’, ‘30′);

?>

Making sure you have included the function in the top of the page which was shown earlier in the post. This will now grab the targeting page and display it in your browser.

Hope you have learnt something from this tutorial. Any questions please post a comment and i will get back to you as soon as possible.


你可能感兴趣的:(content)