dtt78245 2015-03-02 21:15
浏览 186
已采纳

使用php curl的HTTP错误403

I want to do a http request with curl but can't get a valid response from the server.

the $url variable is filled with the string: "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;
}
  • 写回答

1条回答

  • doxn43207 2015-03-02 21:28
    关注

    That website checks for a valid User-Agent header which the cURL PHP client does not provide by default (though the commandline client does). To overcome that you can add:

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

    or similar.

    Edit: full code succesfully tested:

    <?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');
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题