Categories
Stay Ahead with Expert Blockchain Insights on CryptoIQ Blog

Bitcoin & Blockchain Programming. RPCs via PHP

Connecting to Bitcoin Core via RPC using PHP

This tutorial will show you how to communicate with bitcoind programmatically using RPC (Remote Procedure Call) in PHP.

Prerequisites

Make sure you have PHP installed on your system. You can install it using:

sudo apt-get install php5

To verify your PHP installation:

php --version

Setup

Required Components

  1. The jsonRPCClient.php library
    • Download from jsonrpcphp.org
    • This handles the JSON-RPC communication with bitcoind

Configuration

You’ll need the following credentials from your bitcoin.conf file:

  • Username: bitcoin_user
  • Password: qwertyu873nld9j4n09sn3mm
  • IP: 127.0.0.1 (localhost)
  • Port: 18332 (testnet)

Basic Implementation

1. Creating the RPC Connection

First, establish a connection to bitcoind:

<?php
require_once 'jsonRPCClient.php';

$bitcoin = new jsonRPCClient('http://bitcoin_user:[email protected]:18332/');

2. Getting Block Count

A simple example to retrieve the current block count:

$blockcount = ($bitcoin->getblockcount());
print "current block count is: $blockcount \n";

3. Getting Node Information

Retrieve and display node information:

$info = ($bitcoin->getinfo());

You can print specific information:

print "version " . $info['version'] . "\n";

Or iterate through all available information:

foreach ($info as $key => $val) {
    print "$key = $val\n";
}

Complete Example

Here’s a complete script that combines all the above functionality:

<?php
require_once 'jsonRPCClient.php';
// json RPC library 

$bitcoin = new jsonRPCClient('http://bitcoin_user:[email protected]:18332/');

$blockcount = ($bitcoin->getblockcount());
print "current block count is: $blockcount \n";

$info = ($bitcoin->getinfo());
print "version " . $info['version'] . "\n";

foreach ($info as $key => $val) {
    print "$key = $val\n";
}
?>

Next Steps

With this foundation, you can now:

  1. Connect to bitcoind programmatically
  2. Issue commands
  3. Receive and process information
  4. Build more complex applications

In the next tutorial, we’ll explore how to achieve the same objectives using Python instead of PHP.