萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 使用 Stream 發送與接收二進制文件流

場景

兩台伺服器間傳輸文件,不想落地暫存,直接以 HTTP POST 流式傳輸。發送端讀取文件內容作為 Request Body,接收端從 php://input 讀取原始流並寫入磁碟。

發送端 sendStreamFile.php

<?php
function sendStreamFile($url, $file) {
    if (!file_exists($file)) return false;

    $opts = [
        'http' => [
            'method'  => 'POST',
            'header'  => 'Content-Type: application/octet-stream', // 二進制流
            'content' => file_get_contents($file)                  // 直接讀入記憶體,大文件請用 fopen 流式
        ]
    ];
    $context  = stream_context_create($opts);
    $response = file_get_contents($url, false, $context);
    $ret      = json_decode($response, true);
    return $ret['success'] ?? false;
}

var_dump(sendStreamFile('https://localhost/receiveStreamFile.php', 'send.txt'));
?>

接收端 receiveStreamFile.php

<?php
function receiveStreamFile($savePath) {
    // 兼容 PHP 5.6+ 已棄用 $HTTP_RAW_POST_DATA
    $streamData = file_get_contents('php://input');

    if ($streamData === '') return false;

    $bytes = file_put_contents($savePath, $streamData);
    return $bytes !== false;
}

$receiveFile = 'receive.txt';
$ret = receiveStreamFile($receiveFile);
echo json_encode(['success' => (bool)$ret]);
?>

關鍵點

  • php://input 可讀取原始 POST 數據,不依賴 $_POST 解析,適合非表單格式(JSON、XML、二進制)
  • 大文件傳輸時,發送端建議改用 fopen($file, 'rb') 配合 stream_copy_to_stream 避免記憶體耗盡
  • 接收端同理可用 fopen($savePath, 'wb') + stream_copy_to_stream 邊讀邊寫
  • 生產環境需加入 Token 驗證、傳輸加密(HTTPS)、斷點續傳機制

大文件流式傳輸改進版(發送端)

$fp = fopen($file, 'rb');
$opts = [
    'http' => [
        'method' => 'POST',
        'header' => 'Content-Type: application/octet-stream',
    ]
];
$context = stream_context_create($opts);
$out = fopen($url, 'wb', false, $context);
stream_copy_to_stream($fp, $out);
fclose($fp);
fclose($out);
copyright © 萬盛學電腦網 all rights reserved