BlowfishForce
BlowfishForce

Reputation: 9

get last bitcoin price bitstamp

My goal is fairly simple, this is a PHP file and I included it into my header because I want to display the last bitcoin price using bitstamp.net not any other bitcoin exchange prices.

<?php
function getprice($url){
    $decode = file_get_contents($url);
    return json_decode($decode, true);
}

$btcUSD = getPrice('https://www.bitstamp.net/api/ticker/ '); //bitstamp 
$btcPrice = $btcUSD["last"];

$tempround = round($btcPrice, 2);
$btc_Display = "$".$tempround;
?>

Well, this seems to work, but some times upon refreshing the page I get an error.

Warning: file_get_contents(https://www.bitstamp.net/api/ticker/ ):
failed to open stream: HTTP request failed! HTTP/1.1 400 BAD_REQUEST in C:\xampp\htdocs\hidden\btcprice.php on line 3

The error doesn't happen often its very random in timing, but what does it mean and how can I prevent it?

It took me a while to get the error because I don't know what is causing it. I'm curious how to prevent it, am I leaving something out? I used a guide to learn how to do this that got the last bitcoin price from btc-e, but I don't want to use btc-e. I have to use bitstamp last price.

Also no JavaScript is allowed (or should I say I'm trying to avoid JavaScript for this little project) and I don't understand PHP OOP stuff, so please no examples in that.

Upvotes: 0

Views: 1423

Answers (1)

Bobface
Bobface

Reputation: 2952

Your code is working for me. The w3.org defines 400 as follows:

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

However, that can happen when you use a Web-Api. Espacially Api's from Bitcoin-exchanges can be pretty unstable and answer with errors from time to time, according to my own experience. How RobotMind already mentioned, you should put a

try
{
}
catch
{
}

around the getPricefunction.

Another option is to use Curl. This way you can easily access the Status-Code and react accordingly if an error should happen.

Upvotes: 1

Related Questions