3

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
  • I grouped the information you give to the top of the question and removed unnecessary information such as 'thanks'. also formatting code helps understanding faster what could be the problem. Commented Mar 6, 2015 at 16:54

1 Answer 1

2

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

?>
Sign up to request clarification or add additional context in comments.

1 Comment

super answer "curl/7.39.0" is magical agent i dont know what is meaning of this agent but after testing 50-100 user agent only this works for me.thanks alot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.