


PHP implements content parsing for interaction with Ethereum through JSON-RPC
The content of this article is about the content analysis of PHP interacting with Ethereum through JSON-RPC. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Since last year, we are developing blockchain (Blockchain) business. Having recently used Ethereum and working with PHP, I thought we'd chat about this topic.
There is a premise here:
1. Understand the blockchain
2. Have an understanding of programming languages
Text:
1. Development environment
We will use Ubuntu 14.04 LTS. After installing the operating system, enter the predetermined commands.
$ sudo apt-get update $ sudo apt-get upgrade
After that I set up SSH, iptables, ntp, etc.
Then comes Apache PHP. The PHP version will be 5.5.
$ sudo apt - get install php 5 libapache 2 - mod - php 5 php 5 - curl
2. Introduction to Ethereum
This time we will use the Ethereum node made in GO language, go-ethereum
referred to as geth.
First let's add a repository.
$ sudo apt-get install software-properties-common $ sudo add-apt-repository -y ppa:ethereum / ethereum $ sudo add-apt-repository -y ppa:ethereum / ethereum-dev
After that, just install it.
$ sudo apt-get update $ sudo apt-get install ethereum
Start geth immediately after the installation is completed.
First, create a data directory and describe the settings for the first block (the genesis block).
$ mkdir~ / eth_private_net $ vim~ / eth_private_net / my_genesis.json { “nonce”:“0x0000000000000042”, “timestamp”:“0x0”, “parentHash”:“0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000”, “extraData”:“0x0”, “gasLimit”:“0xffffffff”, “难度”:“0x4000”, “mixhash”:“0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000”, “coinbase”:“0x3333333333333333333333333333333333333333”, “alloc”:{} }
Next, create the Genesis block and start geth.
$ geth --datadir "/home/yoshida/eth_private_net" init /home/yoshida/eth_private_net/my_genesis.json $ geth --networkid 57598955 --port 8955 --nodiscover --datadir "/home/yoshida/eth_private_net" console 2>> /home/yoshida/eth_private_net/geth_err.log
When in console mode, the startup is successful.
Specifies several options, the explanations are summarized below.
networkid, connect to public node.
port, it is a port used for standby. I changed it to 4 digits.
nodiscover, this is a setting that prevents nodes from automatically viewing.
datadir, specifies the directory where the blockchain stores data.
console, start the console at the same time.
Okay, let’s prepare for the next call to PHP, but before that let’s do a little more preparation on the geth side.
3. Prepare for JSON-RPC calls
Access from PHP via JSON-RPC. Here we will set up the neighborhood.
First, the current account information will be obtained. We also use the geth console we last started.
> eth.accounts []
We haven't created an account yet, so we need to create it.
> personal.newAccount("password") "0xb83fa0d1c6b34a42f900cca5a32400c3b6f69f4b" > eth.accounts ["0xb83fa0d1c6b34a42f900cca5a32400c3b6f69f4b"]
Account now created. We set it up so that we can get rewards when mining.
> miner.setEtherbase(eth.accounts [0])
Next, since the current node does not allow RPC calls, add an option and start it again. First let's wrap up geth.
> exit
Let’s add options and restart
$ geth --networkid 57598955 --port 8955 --nodiscover --rpc --rpcaddr "0.0.0.0" --rpcport "8956" --rpccorsdomain "*" --rpcapi "eth,net,web3,personal" --datadir "/home/yoshida/eth_private_net" console 2>> /home/yoshida/eth_private_net/geth_err.log
Added several options for rpc. The explanation is as follows.
rpc, allows RPC backup.
rpcaddr, used for RPC backup IP address.
rpcport, the port used to listen to RPC. I lowered the port number to 4 digits.
rpccorsdomain, the domain that allows access to RPC. Note that when publishing a node, if it is "*" it will allow everything.
The node side is now ready. Next will be the call from PHP.
4. Access from PHP
The last thing is why access from PHP but have them because it is quite difficult to use this when you write code.
As you can see in the README, you only need to create a class.
Let's use it by placing it in the same directory as the test script.
$ cd /home/yoshida/php-eth/ $ ls -l ethereum.php json-rpc.php $ vim test.php <?php require_once 'ethereum.php'; $ethereum = new Ethereum('localhost', '8956'); print_r($ethereum->eth_accounts());
When we run this script, there should be a list of accounts as follows.
$ php test.php Array ( [0] => 0xb83fa0d1c6b34a42f900cca5a32400c3b6f69f4b )
If you cannot connect, please check the port settings, etc.
So far, we have explained it simply, but does it feel like developing with PHP is surprisingly easy?
Related recommendations:
How the browser obtains relevant data through the JSON-RPC interface of the Bitcoin Core client
A simple json rpc framework example implemented in php
The above is the detailed content of PHP implements content parsing for interaction with Ethereum through JSON-RPC. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
