Alternative to file_get_contents() using cUrl

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值