专业编程基础技术教程

网站首页 > 基础教程 正文

PHP与Web3:智能合约开发全栈实战(php和web)

ccvgpt 2025-03-18 20:13:23 基础教程 2 ℃

技术段位: 区块链全栈必修
核心价值:PHP赋能DApp开发 + 智能合约安全加固
适配场景:DeFi协议 / NFT平台 / DAO治理

PHP与Web3:智能合约开发全栈实战(php和web)


一、开发环境闪电搭建

1. 区块链本地测试网

# 安装Ganache(以太坊测试链)  
npm install -g ganache-cli  

# 启动私有链(支持伦敦升级后Gas计算)  
ganache-cli --chain.chainId 1337 --hardfork london  

2. PHP Web3开发套件

// 安装web3.php  
composer require web3p/web3.php  

// 连接本地测试链  
$web3 = new Web3\Web3('http://localhost:8545');  
$eth = $web3->eth;  

二、智能合约开发:从投票系统到NFT

1. Solidity合约开发(Voting.sol)

// SPDX-License-Identifier: MIT  
pragma solidity ^0.8.17;  

contract Voting {  
    mapping(address => bool) public voters;  
    mapping(uint => uint) public votesReceived;  

    function vote(uint _candidateId) external {  
        require(!voters[msg.sender], "Already voted");  
        voters[msg.sender] = true;  
        votesReceived[_candidateId] += 1;  
    }  

    function getVotes(uint _candidateId) external view returns (uint) {  
        return votesReceived[_candidateId];  
    }  
}  

2. PHP部署合约到测试链

// 编译合约  
$compiler = new \Ethereum\Compiler('solc');  
$compiled = $compiler->compile('Voting.sol');  

// 部署合约  
$deployTx = [  
    'from' => $account,  
    'gas' => '0x'.dechex(3000000),  
    'data' => '0x'.$compiled['contracts']['Voting']['bin']  
];  

$eth->sendTransaction($deployTx, function ($err, $txHash) use ($eth) {  
    if ($err !== null) throw $err;  
    echo "合约地址:".$txHash;  
});  

三、PHP与合约交互全流程

1. 调用投票函数

// 构建交易数据  
$contractAddress = '0x...';  
$abi = json_decode(file_get_contents('Voting.abi'), true);  
$contract = new Contract($web3->provider, $abi);  

// 执行投票  
$contract->at($contractAddress)->send('vote', [1], [  
    'from' => $voterAddress,  
    'gas' => 500000  
], function ($err, $result) {  
    if ($err) throw new Exception("投票失败: ".$err->getMessage());  
    echo "交易哈希:".$result;  
});  

2. 查询投票结果

$contract->call('getVotes', [1], function ($err, $votes) {  
    echo "候选人1得票数:".hexdec($votes[0]->toString());  
});  

四、进阶实战:NFT铸造平台

1. ERC721合约核心功能

function mintNFT(address _to, string memory _tokenURI) external payable {  
    require(msg.value >= 0.1 ether, "Insufficient ETH");  
    _tokenIds.increment();  
    uint newTokenId = _tokenIds.current();  
    _mint(_to, newTokenId);  
    _setTokenURI(newTokenId, _tokenURI);  
}  

2. PHP集成MetaMask支付

// 生成前端调用代码  
$mintJS = << {  
    const contract = new web3.eth.Contract(abi, '$contractAddress');  
    contract.methods.mintNFT(accounts[0], ipfsHash)  
    .send({ from: accounts[0], value: web3.utils.toWei('0.1', 'ether') })  
    .on('transactionHash', hash => {  
        console.log('交易已发送:', hash);  
    });  
});  
JS;  

五、安全加固:防御重入攻击

1. 危险代码模式

// 漏洞代码:先转账后更新状态  
function withdraw() external {  
    uint amount = balances[msg.sender];  
    (bool success, ) = msg.sender.call{value: amount}("");  
    require(success, "Transfer failed");  
    balances[msg.sender] = 0;  
}  

2. 安全加固方案

// 使用Checks-Effects-Interactions模式  
function withdraw() external {  
    uint amount = balances[msg.sender];  
    balances[msg.sender] = 0; // 先更新状态  
    (bool success, ) = msg.sender.call{value: amount}("");  
    require(success, "Transfer failed");  
}  

六、今日挑战

任务:开发一个拍卖智能合约,要求:

  1. PHP实现竞标功能
  2. 防止最后时刻狙击竞价
  3. 支持ERC20代币支付

合约要求

  • 拍卖结束时最高出价者获得NFT
  • 竞价延长机制:最后5分钟内新出价延长拍卖时间10分钟

数据样例

struct Auction {  
    address nftAddress;  
    uint tokenId;  
    address highestBidder;  
    uint highestBid;  
    uint endTime;  
}  

充电进度: Web3全栈掌握度 +75%
欢迎小伙伴在评论区互动

五分钟快充,知识加速度!碎片时间高效充电,轻松夯实学习根基!核心知识点闪电入脑,基础技能即刻升级。每天五分钟,让知识像电流般激活思维,学习不费力,成长看得见。

更多相关技术知识,可以微信搜 “技术快充吧” 关注学习更多技术知识。

Tags:

最近发表
标签列表