Miguel Miguel - 6 months ago 30
PHP Question

File_get_contents, curl not working

Something strange is going on, i would like to know why.

On this url: http://api.promasters.net.br/cotacao/v1/valores?moedas=USD&alt=json, which works well in the browser. when i tried to retrieve the content with php:

echo file_get_contents('http://api.promasters.net.br/cotacao/v1/valores?moedas=USD&alt=json');


printed nothing, with
var_dum(...) = string(0) ""
, so i went a little further and used:

function get_page($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, True);
curl_setopt($curl, CURLOPT_URL, $url);
$return = curl_exec($curl);
curl_close($curl);
return $return;
}

echo get_page('http://api.promasters.net.br/cotacao/v1/valores?moedas=USD&alt=json');


Also printed nothing, so i tried python (3.X):

import requests
print(requests.get('http://api.promasters.net.br/cotacao/v1/valores?moedas=USD&alt=json').text)


And WORKED. Why is this happening? What's is going on?

Answer

It looks like they're blocking the user agent.

You can fake this by setting it to something else like Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1

<?php
function get_page($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, True);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl,CURLOPT_USERAGENT,'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1');
    $return = curl_exec($curl);
    curl_close($curl);
    return $return;
}

echo get_page('http://api.promasters.net.br/cotacao/v1/valores?moedas=USD&alt=json');
Comments