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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序