php 卷曲的 HTTP 错误 403

HTTP Error 403 with php curl

我想用 curl 做一个 http 请求,但无法从服务器获得有效响应。

$url 变量用字符串填充:"http://www.transfermarkt.de/borussia-dortmund/startseite/verein/16/index.html"

function request($url) {

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($ch);
    $statuscode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $statustext = curl_getinfo($ch);
    curl_close($ch);
    if($statuscode!=200){
    echo "HTTP ERROR ".$statuscode."<br>";
    echo "<pre>";
    echo var_dump($statustext);
    echo "</pre>";
    return "false";

    }
    return $result;
}

该网站会检查 cURL PHP 客户端默认不提供的有效 User-Agent header(尽管命令行客户端提供)。要克服这个问题,您可以添加:

curl_setopt($ch, CURLOPT_USERAGENT, 'User-Agent: curl/7.39.0');

或类似。

编辑:完整代码已成功测试:

<?php

function request($url){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        curl_setopt($ch, CURLOPT_USERAGENT, 'User-Agent: curl/7.39.0');

        $result = curl_exec($ch);
        $statuscode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $statustext = curl_getinfo($ch);
        curl_close($ch);
        if($statuscode!=200){
        echo "HTTP ERROR ".$statuscode."<br>";
        echo "<pre>";
        echo var_dump($statustext);
        echo "</pre>";
        return "false";

        }
        return $result;
    }

echo request('http://www.transfermarkt.de/borussia-dortmund/startseite/verein/16/index.html');

?>