Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP Error 403 with php curl

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;
}
like image 907
juergenBVB Avatar asked May 03 '26 18:05

juergenBVB


1 Answers

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');

?>
like image 55
Hans Z. Avatar answered May 05 '26 08:05

Hans Z.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!