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.
使用cURL替换file_get_contents
本文介绍了一种使用cURL获取网页内容的方法,作为PHP内置函数file_get_contents的替代方案。通过定义三个参数(url、referer、timeout),实现从指定URL抓取内容并返回字符串。
3689

被折叠的 条评论
为什么被折叠?



