Kayla Flam
Kayla Flam

Reputation: 11

HTTP/1.0 403 Forbidden error message when using Wikipedia API

I'm trying to use an API to search wikipedia for a word that the user who fills out my form typed in. So, if they typed "cat" into the form, the API would then search wikipedia for entries containing the word "cat". I got it to work, but now I"m getting this message:

Warning: file_get_contents(http://en.wikipedia.org/w/api.php?action=opensearch&search=parrott): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in /var/www/html/flam1-api.php on line 22

I read about perhaps needing a user-agent, but I'm not sure what exactly to do. Here's my code:

    echo "<h1>Which LOLcat are you? Results!</h1>";
    $visit_id = $_COOKIE['visit_id'];
    $all_my_variables = json_decode(file_get_contents("/var/www/html/data/$visit_id.json"));
    //var_dump($all_my_variables);
    $animal = $all_my_variables ->favoriteanimal;
    echo "When searching wikipedia entries on your favorite animal, which is a $animal, we got the results:<br>";
     $website = file_get_contents('http://en.wikipedia.org/w/api.php?action=opensearch&search='.urlencode($animal).'');

        echo $website[0];   

I definitely appreciate any help on this!

Upvotes: 1

Views: 1480

Answers (2)

Nesim Razon
Nesim Razon

Reputation: 9794

Some sites blocks using file_get_contents. I don't have a chnace to test now, but try using this function isntead of file_get_contents.

function get_url_contents($url){
        $crl = curl_init();
        $timeout = 5;
        curl_setopt ($crl, CURLOPT_URL,$url);
        curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
        $ret = curl_exec($crl);
        curl_close($crl);
        return $ret;
}

Upvotes: 1

user149341
user149341

Reputation:

You need to set a user agent (perhaps by using the curl extension instead of file_get_contents). The default user agent used by file_get_contents is explicitly blocked, as it's often associated with abusive behavior.

Upvotes: 3

Related Questions