Now, make a PHP script file index.php in your project directory and copy-paste the following in it.
connecting to ethereum with php
<?
require_once "vendor/autoload.";
use Web3\Web3;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;
$web3 = new Web3(new HttpProvider(new HttpRequestManager("ADD_YOUR_ETHEREUM_NODE_URL")));
$eth = $web3->eth;
$eth->blockNumber(function ($err, $data) {
echo "Latest block number is: ". $data . " \n";
});
?>
<?
require_once "vendor/autoload.";
use Web3\Web3;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;
$web3 = new Web3(new HttpProvider(new HttpRequestManager("ADD_YOUR_ETHEREUM_NODE_URL")));
$eth = $web3->eth;
$eth->blockNumber(function ($err, $data) {
echo "Latest block number is: ". $data . " \n";
});
?>
<?
require_once "vendor/autoload.";
use Web3\Web3;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;
$web3 = new Web3(new HttpProvider(new HttpRequestManager("ADD_YOUR_ETHEREUM_NODE_URL")));
$eth = $web3->eth;
$eth->blockNumber(function ($err, $data) {
echo "Latest block number is: ". $data . " \n";
});
?>
Make sure to replace `ADD_YOUR_ETHEREUM_NODE_URL` with the HTTP provider from the section above.
Explanation of the code above.
Line 1: Starting the PHP script with PHP opening tag.
Line 3-7: Importing the installed dependencies.
Line 9: Initializing the web3 instance, a HttpProvider instance, and supplying the node URL.
Line 11: Making a new variable eth and connecting the web3 instance with eth to use eth methods using our node.
Line 13: Getting the latest block number from the chain using the blockNumber() method, which under the hood uses eth_blockNumber. We then print the block number along with a string.
Save the file and run the PHP script by typing the following in your terminal/cmd:
connecting to ethereum with php
$ php index.php
$ php index.php
If everything goes well, you will see an output that shows the latest block number.