How to Query an ElectrumX Server with PHP

By | May 25, 2020

Spent several hours today figuring out how to interact with an ElectrumX server, and it resulted into just several lines of code. I hope this will save someone time. I will show 2 versions – for TCP and SSL connection to ElectrumX server.

Here is the TCP one:

<?php

// Preparing a TCP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// connecting to your socket
socket_connect($socket, "localhost", 47001);

// Here is a sample JSON query
$query='{"id": "blk", "method": "blockchain.estimatefee", "params":["5"]}';

// Sending query to server
socket_write($socket, $query."\n");

// Receiving result from your query (I think it should not exceed 10 Kb)
socket_recv($socket, $value, 10240, MSG_PEEK);

$result=json_decode($value);

print_r($result);

socket_close($socket);

?>

If you prefer to connect to your server with SSL (I suppose you have a self-signed certificate), here is your code:

<?php

// Defining host, port, and timeout
$host = '127.0.0.1';
$port = 47002;
$timeout = 30;

// Setting context options
$context = stream_context_create();
stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
stream_context_set_option($context, 'ssl', 'verify_peer_name', false);

// JSON query for fee estimation in 5 blocks
$query='{"id": "blk", "method": "blockchain.estimatefee", "params":["5"]}';

if ($socket = stream_socket_client('ssl://'.$host.':'.$port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context)
) {
    fwrite($socket, $query."\n");
    $value=fread($socket,10240);

	$result=json_decode($value);

	print_r($result);

    fclose($socket);
} else {
   echo "ERROR: $errno - $errstr\n";
}

?>

Both scripts are doing the same. You should get something like this in the output:

stdClass Object
(
    [jsonrpc] => 2.0
    [result] => 0.00106033
    [id] => blk
)

Leave a Reply

Your email address will not be published. Required fields are marked *