Skip to content

Everything for WordPress, web development — and beyond

💰 PHP API for getting the current Bitcoin price in 2026: from a simple script to a production solution

💰 PHP API for getting the current Bitcoin price in 2026: from a simple script to a production solution

The site accepts cryptocurrency, and the exchange rate swings by a few percent within half an hour. The client wants to see the current Bitcoin price in fiat currency right in the interface, not a screenshot from an exchange, but a live number from the API.

Manually monitoring the rate through a CoinMarketCap tab takes time and provides delayed data. Meanwhile, ready-made crypto plugins are often bloated: ads, unnecessary requests, locked to a single source.

Below are two ways to get the current Bitcoin price via PHP: from a basic 10-line script to a production-ready solution with caching and source selection. No paid plans, no 40-megabyte SDK.

💡 Quick overview:

  • Choosing an API source: Bitpay (free, no key required) or CoinGecko (more data, also free)
  • Writing a PHP script with file_get_contents or cURL, both approaches explained
  • Adding error handling and file caching for 5 minutes to avoid hitting the API on every page load

What is a crypto quote API and why does a PHP developer need it

Crypto exchange and aggregator APIs return the current rate over HTTP: you make a GET request and receive JSON with a "BTC/USD" pair and a number. No WebSocket or subscription required: a regular PHP script on cheap hosting handles it just fine.

Typical scenarios where this is useful:

  • Payment gateway. Show the user: "Amount due: 0.00031 BTC," with the rate pulled from an API rather than made up.
  • Dashboard. An online store admin panel with a "Cryptocurrency rates" block.
  • Portfolio tracker. You hold 5 coins, and a script updates their total value once a minute.

For this article, two sources with free access and no registration were chosen: Bitpay and CoinGecko. Both work over HTTPS, return JSON, and require no API key at the basic level.

Graph showing Bitcoin transaction count over a month

Step 1: getting the rate via Bitpay API

Bitpay is a payment processor for Bitcoin. It has a public endpoint /api/rates that returns BTC rates for 150+ fiat currencies in a single JSON array. No token, no request limits for basic usage.

Simple approach: file_get_contents

The shortest working code. Add it to a bitcoin-rates.php file in your site root and open it in a browser:

1<?php
2$url = "https://bitpay.com/api/rates";
3$json = json_decode(file_get_contents($url), true);
4
5foreach ($json as $item) {
6 if ($item['code'] === 'USD') {
7 echo '1 BTC = $' . $item['rate'] . "\n";
8 }
9 if ($item['code'] === 'EUR') {
10 echo '1 BTC = €' . $item['rate'] . "\n";
11 }
12}

The script requests the entire rate array, loops through it, and outputs only USD and EUR. file_get_contents() with an HTTPS URL works if the allow_url_fopen = On directive is enabled in php.ini; on most hosting providers it is active by default.

More reliable approach: cURL

file_get_contents does not set timeouts and fails silently on network errors. For a real website, cURL is the better choice:

1<?php
2$ch = curl_init();
3curl_setopt_array($ch, [
4 CURLOPT_URL => 'https://bitpay.com/api/rates',
5 CURLOPT_RETURNTRANSFER => true,
6 CURLOPT_TIMEOUT => 10,
7 CURLOPT_SSL_VERIFYPEER => true,
8]);
9$response = curl_exec($ch);
10$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
11curl_close($ch);
12
13if ($httpCode !== 200 || !$response) {
14 echo 'API temporarily unavailable.';
15 exit;
16}
17
18$data = json_decode($response, true);
19
20foreach ($data as $item) {
21 if ($item['code'] === 'USD') {
22 echo '1 BTC = $' . number_format($item['rate'], 2) . "\n";
23 }
24}

A 10-second timeout, HTTP code check, and number_format for readable output. In practice, a script like this is enough to embed the rate in a site footer or sidebar.

Step 2: alternative source, CoinGecko API

Bitpay only provides rates for BTC and BCH. If you also need Ethereum, Solana, or any other asset from the top 500, connect to CoinGecko API. The free tier allows 10-30 requests per minute without a key.

Simple request for Bitcoin and Ethereum prices

The /api/v3/simple/price endpoint accepts a comma-separated list of coins and currencies via the vs_currencies parameter:

1<?php
2$url = 'https://api.coingecko.com/api/v3/simple/price'
3 . '?ids=bitcoin,ethereum'
4 . '&vs_currencies=usd,eur,rub';
5
6$ch = curl_init();
7curl_setopt_array($ch, [
8 CURLOPT_URL => $url,
9 CURLOPT_RETURNTRANSFER => true,
10 CURLOPT_TIMEOUT => 10,
11]);
12$response = curl_exec($ch);
13curl_close($ch);
14
15$prices = json_decode($response, true);
16
17echo 'BTC: $' . $prices['bitcoin']['usd'] . ' / €' . $prices['bitcoin']['eur'] . "\n";
18echo 'ETH: $' . $prices['ethereum']['usd'] . ' / ₽' . $prices['ethereum']['rub'] . "\n";

The response is compact, containing only the coins and currencies you requested. No looping through 150 entries.

What else CoinGecko can do

  • Historical data: /api/v3/coins/bitcoin/history?date=01-01-2026, the rate on a specific date.
  • Market data: /api/v3/coins/bitcoin, market cap, volume, 24-hour change, circulating supply.
  • Trending coins: /api/v3/search/trending, top search queries for the past day.

For a simple "BTC/USD" rate, the first example is sufficient. If you are building a dashboard, connect to the extended endpoint.

Step 3: caching and protection against API failure

Hitting an external API on every page load is bad practice. The network can hiccup, the CoinGecko server can go down for a minute, and the visitor sees an error instead of the rate.

A robust solution is file caching. The script saves the API response to a local JSON file and updates it once every 5 minutes. All intermediate requests read from the cache, instantly and without external calls.

1<?php
2$cacheFile = __DIR__ . '/btc-cache.json';
3$cacheTime = 300; // 5 minutes
4
5// If cache is fresh — read it
6if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {
7 $data = json_decode(file_get_contents($cacheFile), true);
8 echo '1 BTC = $' . number_format($data['bitcoin']['usd'], 2);
9 echo ' (cached, updated ' . date('H:i:s', filemtime($cacheFile)) . ')';
10 exit;
11}
12
13// Cache is stale or missing — request API
14$ch = curl_init();
15curl_setopt_array($ch, [
16 CURLOPT_URL => 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd',
17 CURLOPT_RETURNTRANSFER => true,
18 CURLOPT_TIMEOUT => 10,
19]);
20$response = curl_exec($ch);
21$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
22curl_close($ch);
23
24if ($httpCode !== 200 || !$response) {
25 // API is down — serve stale cache if available
26 if (file_exists($cacheFile)) {
27 $data = json_decode(file_get_contents($cacheFile), true);
28 echo '1 BTC = $' . number_format($data['bitcoin']['usd'], 2);
29 echo ' (stale cache — API did not respond)';
30 exit;
31 }
32 echo 'No data available. Please try again later.';
33 exit;
34}
35
36// Save fresh response and output
37file_put_contents($cacheFile, $response);
38$data = json_decode($response, true);
39echo '1 BTC = $' . number_format($data['bitcoin']['usd'], 2);
40echo ' (fresh data)';

Note that the script checks the cache first and only calls the API when necessary. If the API does not respond, the last saved rate is served with a "stale cache" label. The visitor sees a number, not a blank page with an error.

Before deploying to a production site, make sure PHP has write permissions to the script's directory. Also make a full backup, since the script writes a file to disk.

The video above provides a visual breakdown of the CoinGecko API with real-time request and response examples. It is suitable if you are working with a crypto API for the first time and want to see the full cycle: from GET request to JSON parsing.

⁉️🤔 Frequently asked questions

Which API should I choose, Bitpay or CoinGecko?

If you only need the Bitcoin to dollar rate, go with Bitpay. It is simpler, returns a response as a single array without parameters, and has no limits. If you plan to work with a dozen coins or display charts, choose CoinGecko: more data, flexible endpoints, and a free tier that covers the needs of a small project.

Does Bitpay API require an API key?

The public endpoint /api/rates does not require a key. It is an open endpoint used by wallets and exchanges to display rates. Commercial Bitpay endpoints (creating invoices, accepting payments) require a token, but they are not needed for simply retrieving rates.

Why not CoinMarketCap API?

CoinMarketCap's free tier requires registration and a key. The limit is 10,000 requests per month, which is enough for a small project. However, for a "start from scratch with no registration" approach, Bitpay and CoinGecko are more convenient: copy the URL, paste it into your code, and it works.

What if my hosting blocks file_get_contents for external URLs?

Switch to cURL, which is available on virtually any hosting. If cURL is also disabled (rare in 2026), ask your host about enabling curl.so in PHP extensions. An alternative is to use wp_remote_get() inside WordPress; this function works through the core HTTP API and automatically selects an available transport.

How often are the rates updated in the API?

Bitpay updates the rate with every request; the figures reflect the current market spread. CoinGecko updates data once every 30-60 seconds for the simple price endpoint. For website display purposes, an update frequency of "once every 5 minutes" is more than sufficient; the crypto market is volatile, but not so much that second-by-second fluctuations matter for an informational block.

Which API to choose for your task

Bitpay and CoinGecko address different needs without directly competing:

  • If you are building a payment form with "BTC → USD" conversion, use Bitpay: a single URL line, minimal code, always fresh rates.
  • If you are building a dashboard with charts and a portfolio of 10 coins, use CoinGecko: batch price requests, historical data, market cap and volume in a single call.
  • If you need the fastest possible start with no external dependencies, use Bitpay without cURL via file_get_contents: 10 lines of code and the rate is on your page.

Start simple: copy the first example from this article, replace the currency with your own, and open it in a browser. If it works, wrap it in caching using the template from step 3 and deploy to your production site. Let us know in the comments which API you ended up choosing.