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 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题