如何使用 CURL 而不是 file_get_contents? [英] How to use CURL instead of file_get_contents?

查看:31
本文介绍了如何使用 CURL 而不是 file_get_contents?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 file_get_contents 函数来获取并在我的特定页面上显示外部链接.

I use file_get_contents function to get and show external links on my specific page.

在我的本地文件中一切正常,但我的服务器不支持 file_get_contents 函数,所以我尝试使用 cURL 和以下代码:

In my local file everything is okay, but my server doesn't support the file_get_contents function, so I tried to use cURL with the below code:

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

 echo file_get_contents_curl('http://google.com');

但它返回一个空白页.怎么了?

But it returns a blank page. What is wrong?

推荐答案

试试这个:

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

这篇关于如何使用 CURL 而不是 file_get_contents?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆