php file_get_contents($url) & turns into &

Mubashar Abbas picture Mubashar Abbas · May 8, 2015 · Viewed 11.7k times · Source

I am trying to make a request to the coinbase api like this

$url = "https://api.gdax.com/products/BTC-USD/candles?start=".date($format,$starting_date)."&end=".date($format,$ending_date)."&granularity=".$granularity;

and then I pass that in file_get_contents($url) but it gives me an error

file_get_contents(https://api.gdax.com/products/BTC-USD/candles?start=2015-05-07&end=2015-05-08&granularity=900): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request.

The problem of course is when the '&' gets changed into '&'.

Answer

Ilgıt Yıldırım picture Ilgıt Yıldırım · May 8, 2015

It seems you need define an user agent. Try this;

$url = "https://api.gdax.com/products/BTC-USD/candles?start=2015-05-07&end=2015-05-08&granularity=900";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

var_dump($result);

If you still insist on using file_get_contents then it is still possible to use user agent;

$url = "https://api.gdax.com/products/BTC-USD/candles?start=2015-05-07&end=2015-05-08&granularity=900";

$options = array(
    "http"=>array(
        "header"=>"User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad
    )
);

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

For more information you can check file_get_contents and stream_context_create (for using headers) documentation