在 PHP 開發中,處理檔案傳輸是常見需求。當檔案較大或需避免記憶體溢位時,採用串流方式傳輸檔案是最佳選擇。本文將詳細介紹如何使用 PHP 實現檔案的串流發送與接收,包含完整程式碼範例與關鍵技術點解析。
PHP 的串流機制允許我們以資料流方式讀寫檔案,而非一次性載入整個檔案到記憶體。這對於大型檔案傳輸尤為重要,能有效降低記憶體佔用並提升效能。
發送端使用 stream_context_create() 建立 HTTP POST 請求上下文,將檔案內容作為請求主體發送:
<?php
/**
* PHP 發送串流檔案
* @param string $url 接收端 URL
* @param string $file 要發送的檔案路徑
* @return bool 傳輸是否成功
*/
function sendStreamFile($url, $file) {
if (!file_exists($file)) {
return false;
}
$opts = [
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => file_get_contents($file)
]
];
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
$result = json_decode($response, true);
return $result['success'] ?? false;
}
// 使用範例
$result = sendStreamFile('https://localhost/receiveStreamFile.php', 'send.txt');
var_dump($result);
?>
接收端透過 php://input 讀取原始 POST 資料流,並儲存至本地檔案:
<?php
/**
* PHP 接收串流檔案並儲存
* @param string $receiveFile 儲存檔案名稱
* @return bool|int 寫入位元組數或 false
*/
function receiveStreamFile($receiveFile) {
// 相容不同 PHP 版本獲取原始 POST 資料
$streamData = $GLOBALS['HTTP_RAW_POST_DATA'] ?? '';
if (empty($streamData)) {
$streamData = file_get_contents('php://input');
}
if ($streamData !== '') {
return file_put_contents($receiveFile, $streamData);
}
return false;
}
// 使用範例
$receiveFile = 'receive.txt';
$result = receiveStreamFile($receiveFile);
echo json_encode(['success' => (bool)$result]);
?>
對於高併發場景,可考慮使用 stream_set_blocking() 設定非阻塞模式,搭配 stream_select() 實現多路複用,或採用 Swoole、ReactPHP 等異步框架提升併發處理能力。
PHP 串流檔案傳輸透過 php://input 與串流上下文機制,實現了高效、低記憶體佔用的檔案傳輸方案。掌握這項技術對於構建高效能的檔案處理系統、API 介面及分散式應用具有重要價值。實際部署時請務必加強安全防護與錯誤處理機制,確保系統穩定可靠運行。