File_get_contents, curl not working

Something strange is happening, and I would like to know why.

At this URL: http://api.promasters.net.br/cotacao/v1/valores?moedas=USD&alt=json , which works fine in the browser, but when I tried to get the content using php:

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

Nothing printed, var_dump(...) = 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');

Nothing is printed either, 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 WORKING. Why is this happening? What's happening?

+4
source share
2 answers

It looks like they are blocking the user agent or its absence, given that php curl and file_get_contentsdoes not seem to set a value in the request header.

, - 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');
+2

.

URL- CLI Curl .

script file_get_contents script, getallheaders:

<?php
file_put_contents('/tmp/request_headers.txt', var_export(getallheaders(),true));

:

array (
  'Host' => 'localhost',
)

,

$ curl -v URL

file_get_contents. , .

<?php
$opts = array(
    'http'=>array(
    'method'=>"GET",
    'header'=>
      "User-Agent: examplebot\r\n"
    )
);
$context  = stream_context_create($opts);
$response = file_get_contents($url, false , $context);

.

+2

All Articles