PHP 怎么PHP IPFS

wen PHP项目 1

本文目录导读:

PHP 怎么PHP IPFS

  1. 安装IPFS环境
  2. 使用PHP执行IPFS命令
  3. 完整示例:文件上传和下载
  4. 注意事项

我来详细说明如何在PHP中使用IPFS。

安装IPFS环境

首先需要在服务器上安装IPFS:

# 下载IPFS
wget https://dist.ipfs.io/go-ipfs/v0.12.0/go-ipfs_v0.12.0_linux-amd64.tar.gz
# 解压
tar -xvzf go-ipfs_v0.12.0_linux-amd64.tar.gz
# 移动到系统路径
cd go-ipfs
sudo mv ipfs /usr/local/bin/
# 初始化IPFS
ipfs init

使用PHP执行IPFS命令

exec()函数直接调用

<?php
class IPFS {
    private $apiUrl;
    private $ipfsPath;
    public function __construct($apiUrl = 'http://localhost:5001/api/v0/', $ipfsPath = '/usr/local/bin/ipfs') {
        $this->apiUrl = $apiUrl;
        $this->ipfsPath = $ipfsPath;
    }
    // 添加文件到IPFS
    public function addFile($filePath) {
        $command = "{$this->ipfsPath} add " . escapeshellarg($filePath);
        $output = shell_exec($command);
        // 解析输出获取Hash
        preg_match('/added\s+(\w+)\s+/', $output, $matches);
        return isset($matches[1]) ? $matches[1] : null;
    }
    // 添加字符串内容到IPFS
    public function addContent($content) {
        $tempFile = tempnam(sys_get_temp_dir(), 'ipfs_');
        file_put_contents($tempFile, $content);
        $hash = $this->addFile($tempFile);
        unlink($tempFile);
        return $hash;
    }
    // 从IPFS获取文件
    public function getFile($hash, $outputPath = null) {
        if ($outputPath) {
            $command = "{$this->ipfsPath} get " . escapeshellarg($hash) . " -o " . escapeshellarg($outputPath);
        } else {
            $command = "{$this->ipfsPath} cat " . escapeshellarg($hash);
        }
        return shell_exec($command);
    }
    // 获取IPFS对象信息
    public function getInfo($hash) {
        $command = "{$this->ipfsPath} object stat " . escapeshellarg($hash);
        return shell_exec($command);
    }
    // 发布到IPNS
    public function publish($hash) {
        $command = "{$this->ipfsPath} name publish " . escapeshellarg($hash);
        return shell_exec($command);
    }
}
// 使用示例
$ipfs = new IPFS();
// 添加文件
$hash = $ipfs->addFile('/path/to/your/file.txt');
echo "File Hash: " . $hash . "\n";
// 添加字符串内容
$hash = $ipfs->addContent("Hello, IPFS!");
echo "Content Hash: " . $hash . "\n";
// 获取文件内容
$content = $ipfs->getFile($hash);
echo "Content: " . $content . "\n";
?>

使用HTTP API

<?php
class IPFSAPI {
    private $apiUrl;
    public function __construct($apiUrl = 'http://localhost:5001/api/v0/') {
        $this->apiUrl = $apiUrl;
    }
    // 添加文件
    public function add($filePath) {
        $url = $this->apiUrl . 'add';
        if (class_exists('CURLFile')) {
            $postData = ['file' => new CURLFile($filePath)];
        } else {
            $postData = ['file' => '@' . $filePath];
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($response, true);
        return $result['Hash'] ?? null;
    }
    // 获取文件内容
    public function cat($hash) {
        $url = $this->apiUrl . 'cat?arg=' . urlencode($hash);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    // 上传文件内容
    public function putContent($content, $fileName = 'file.txt') {
        $url = $this->apiUrl . 'add?pin=true';
        $boundary = md5(time());
        $eol = "\r\n";
        $data = '';
        $data .= '--' . $boundary . $eol;
        $data .= 'Content-Disposition: form-data; name="file"; filename="' . $fileName . '"' . $eol;
        $data .= 'Content-Type: text/plain' . $eol . $eol;
        $data .= $content . $eol;
        $data .= '--' . $boundary . '--' . $eol;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: multipart/form-data; boundary=' . $boundary,
            'Content-Length: ' . strlen($data)
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($response, true);
        return $result['Hash'] ?? null;
    }
    // 管理固定文件
    public function pinAdd($hash) {
        $url = $this->apiUrl . 'pin/add?arg=' . urlencode($hash);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }
    // 获取节点信息
    public function id() {
        $url = $this->apiUrl . 'id';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }
}
// 使用示例
$ipfs = new IPFSAPI();
// 添加文件
$hash = $ipfs->add('/path/to/file.txt');
echo "File hash: " . $hash . "\n";
$hash = $ipfs->putContent("Hello World!", "hello.txt");
echo "Content hash: " . $hash . "\n";
$content = $ipfs->cat($hash);
echo "Content: " . $content . "\n";
// 获取节点信息
$nodeInfo = $ipfs->id();
print_r($nodeInfo);
?>

使用Composer包

// 安装依赖
// composer require cloutier/php-ipfs-api
<?php
require_once 'vendor/autoload.php';
use Cloutier\PhpIpfsApi\IPFS;
class IPFSManager {
    private $ipfs;
    public function __construct($host = 'localhost', $port = 5001) {
        $this->ipfs = new IPFS($host, $port);
    }
    // 添加文件
    public function addFile($filePath) {
        return $this->ipfs->addFile($filePath);
    }
    // 添加目录
    public function addDirectory($dirPath) {
        return $this->ipfs->addDir($dirPath);
    }
    // 获取文件
    public function getFile($hash) {
        return $this->ipfs->cat($hash);
    }
    // 获取文件到本地
    public function getFileToLocal($hash, $outputPath) {
        $content = $this->ipfs->cat($hash);
        file_put_contents($outputPath, $content);
        return true;
    }
    // 列目录
    public function ls($hash) {
        return $this->ipfs->ls($hash);
    }
    // Pin文件
    public function pinFile($hash) {
        return $this->ipfs->pinAdd($hash);
    }
    // 上传文件(表单上传)
    public function uploadFile($sourcePath) {
        $hash = $this->addFile($sourcePath);
        $this->pinFile($hash);
        return $hash;
    }
}
// 使用示例
$manager = new IPFSManager();
// 上传文件
$hash = $manager->uploadFile('document.pdf');
echo "IPFS Hash: " . $hash . "\n";
// 获取文件
$content = $manager->getFile($hash);
file_put_contents('downloaded_document.pdf', $content);
echo "File downloaded successfully\n";
?>

完整示例:文件上传和下载

<?php
// index.php - 完整的IPFS文件管理系统
class IPFSFileManager {
    private $ipfs;
    public function __construct() {
        // 使用HTTP API
        $this->ipfs = new IPFSAPI();
    }
    // 上传文件
    public function upload($file) {
        if (!isset($file['tmp_name']) || $file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('File upload failed');
        }
        // 上传到IPFS
        $hash = $this->ipfs->add($file['tmp_name']);
        // 固定文件
        $this->ipfs->pinAdd($hash);
        // 保存文件信息到数据库
        $this->saveFileInfo($hash, $file['name'], $file['size']);
        return $hash;
    }
    // 下载文件
    public function download($hash) {
        $content = $this->ipfs->cat($hash);
        // 获取文件信息
        $fileInfo = $this->getFileInfo($hash);
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . ($fileInfo['name'] ?? 'download') . '"');
        header('Content-Length: ' . strlen($content));
        echo $content;
        exit;
    }
    private function saveFileInfo($hash, $name, $size) {
        // 数据库保存逻辑
        // 这里用文件存储示例
        $files = [];
        if (file_exists('files.json')) {
            $files = json_decode(file_get_contents('files.json'), true);
        }
        $files[$hash] = [
            'name' => $name,
            'size' => $size,
            'time' => time()
        ];
        file_put_contents('files.json', json_encode($files));
    }
    private function getFileInfo($hash) {
        if (file_exists('files.json')) {
            $files = json_decode(file_get_contents('files.json'), true);
            return $files[$hash] ?? null;
        }
        return null;
    }
}
// 处理请求
$manager = new IPFSFileManager();
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    try {
        $hash = $manager->upload($_FILES['file']);
        echo json_encode(['success' => true, 'hash' => $hash]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
} elseif (isset($_GET['download'])) {
    $hash = $_GET['download'];
    $manager->download($hash);
} else {
    // 显示上传表单
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>IPFS File Manager</title>
    </head>
    <body>
        <h1>Upload to IPFS</h1>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="file" required>
            <button type="submit">Upload</button>
        </form>
    </body>
    </html>
    <?php
}
?>

注意事项

  1. 安全性:使用 escapeshellarg() 防止命令注入
  2. 权限:确保Web服务器有执行IPFS命令的权限
  3. 性能:大文件建议使用流式处理
  4. 错误处理:始终检查命令执行结果
  5. 配置:确保IPFS守护进程正在运行:ipfs daemon &

选择哪种方式取决于你的具体需求:

  • exec()方式:简单直接,适合小项目
  • HTTP API方式:推荐方式,更安全可靠
  • Composer包:功能完整,适合大型项目

抱歉,评论功能暂时关闭!