在HTTP數據傳送過程當中,傳輸一方直接以二進制流方式傳送文件內容,這樣就造成了一個文件流;php
文件流的接收一般涉及到預約義變量函數 $HTTP_RAW_POST_DATA 和 file_get_contentshtml
/* * PHP 模擬發送流文件 * #param String $receive_url 接收流文件請求的網址 * #param String $send_file_name 發送的文件名,帶路徑 * @return boolean */ function send_stream_file($receive_url, $send_file_name) { if (!file_exists($send_file_name)) { return false; } $options = [ // 設置文件流的參數 'http' => [ 'method' => 'POST', // POST方式傳遞 'header' => 'content-type:application/x-www-form-urlencoded', // POST 方式傳遞數據的標準編碼格式 'content' => file_get_contents($send_file_name), // 將文件寫入到字符串中 ], ]; $context = stream_context_create($options); // 將文件轉換成文件流 $response = file_get_contents($receive_url, false, $context); // 發送請求 if ($response !== false) { return true; } return false; }
/*** * PHP 接收流文件 * @param String $$receive_file_name 接收後保存的文件名 * @return boolean */ function receive_stream_file($receive_file_name) { $stream_data = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : ''; // 使用 $GLOBALS['HTTP_RAW_POST_DATA'] 接收數據 if (empty($stream_data)) { // 不存在數據則使用 file_get_contents 方式來接收 $stream_data = file_get_contents('php://input'); } $result = false; if ($stream_data != '') { $result = file_put_contents($receive_file_name, $stream_data, true); // 保存文件 } return $result; }
/* * 複製文件流到文件中 * @param String $src 源 * @param String $dest 新資源 */ function copy_stream($src, $dest) { $fsrc = fopen($src, 'r'); $fdest = fopen($dest, 'w+'); $len = stream_copy_to_stream($fsrc, $fdest); // 流的複製 fclose($fsrc); fclose($fdest); return $len; }