开发者

using curl from localhost

开发者 https://www.devze.com 2023-02-28 23:45 出处:网络
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.

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 res开发者_如何转开发ponse 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/');
?>


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">
0

精彩评论

暂无评论...
验证码 换一张
取 消