兩台伺服器間傳輸文件,不想落地暫存,直接以 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 邊讀邊寫$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);