doulue7522 2011-04-27 22:32
浏览 81
已采纳

使用来自localhost的curl

I'm just trying to fetch the yahoo web page. www.yahoo.com

If I run my simple script from my hosted site, it works.

If I try it from my localhost. All I get is a header response with: "w32.fp.re1.yahoo.com uncompressed/chunked Wed Apr 27 15:13:48 PDT 2011"

Here is my code:

    <?php

function curl_download($Url){

    // is cURL installed yet?
    if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }


    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();

    // Now set some options (most are optional)

    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);

    // Set a referer
    curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");

    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    // Download the given URL, and return output
    $output = curl_exec($ch);

    // Close the cURL resource, and free system resources
    curl_close($ch);

    return $output;
}


print curl_download('http://www.yahoo.com/');
?>
  • 写回答

1条回答 默认 最新

  • douzhang7728 2011-04-28 00:11
    关注

    Actually, the result starts with

    HTTP/1.1 302 Found
    

    which means there's a Location header in there. And there is:

    Location: http://nl.yahoo.com/?p=us
    

    This is just the response body:

    <!-- w20.fp.ird.yahoo.com uncompressed/chunked Wed Apr 27 17:08:09 PDT 2011 -->
    

    You need to tell cURL to follow Location headers. That's it.

    The name of the option is CURLOPT_FOLLOWLOCATION. Set it to true:

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    

    PS
    After following 1 Location header, this is the start of the response body when I run your code + FOLLOWLOCATION:

    <!DOCTYPE html>
    <html lang="nl-NL" class="y-fp-bg y-fp-pg-grad  bkt732">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services