A simple blockchain implementation in PHP
An introductory PHP example that creates blocks, calculates hashes and checks the integrity of a local chain.
A small blockchain in PHP helps explain links between blocks, hashes and proof of work. This is a teaching example: it keeps one chain in memory and has neither signed transactions nor a decentralized network.
1. Define the Block class
Each block stores data, a timestamp, a nonce, the previous block hash and its own hash. The mine() method searches for a hash with the required number of leading zeros.
<?php
class Block {
public int $timestamp;
public int $nonce = 0;
public string $hash;
public function __construct(
public string $data,
public string $previousHash = '0'
) {
$this->timestamp = time();
$this->hash = $this->calculateHash();
}
public function calculateHash(): string {
return hash('sha256', $this->previousHash . '|' .
$this->timestamp . '|' . $this->data . '|' . $this->nonce);
}
public function mine(int $difficulty): void {
$prefix = str_repeat('0', $difficulty);
while (substr($this->hash, 0, $difficulty) !== $prefix) {
$this->nonce++;
$this->hash = $this->calculateHash();
}
}
}
2. Define the Blockchain class
The chain creates a genesis block and links each new block to its predecessor. isValid() checks hashes, links and proof-of-work requirements for every block.
class Blockchain {
public array $chain = [];
public int $difficulty = 2;
public function __construct() {
$genesis = new Block('Genesis Block');
$genesis->mine($this->difficulty);
$this->chain[] = $genesis;
}
public function addBlock(string $data): void {
$block = new Block($data, $this->chain[count($this->chain) - 1]->hash);
$block->mine($this->difficulty);
$this->chain[] = $block;
}
public function isValid(): bool {
foreach ($this->chain as $index => $block) {
if ($block->hash !== $block->calculateHash()) return false;
if (substr($block->hash, 0, $this->difficulty) !==
str_repeat('0', $this->difficulty)) return false;
if ($index === 0) {
if ($block->previousHash !== '0') return false;
} elseif ($block->previousHash !== $this->chain[$index - 1]->hash) {
return false;
}
}
return true;
}
}
3. Test the chain
Add two blocks, then change the data in the first one. The second validation returns false.
$chain = new Blockchain();
$chain->addBlock('Alice sends 10 coins to Bob');
$chain->addBlock('Bob sends 5 coins to Carol');
var_dump($chain->isValid()); // true
$chain->chain[1]->data = 'Alice sends 1000 coins to Bob';
var_dump($chain->isValid()); // false
This is not a usable cryptocurrency: it lacks digital signatures, transaction rules, persistence, consensus between nodes and protection against many attacks.
Share
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0