PHP傳輸文件流及文件流的保存

什麼是文件流

在HTTP數據傳送過程當中,傳輸一方直接以二進制流方式傳送文件內容,這樣就造成了一個文件流;php

文件流的接收一般涉及到預約義變量函數 $HTTP_RAW_POST_DATA 和 file_get_contentshtml

我在哪些方面用到了文件流

  1. 在開發微信公衆平臺系統的時候用到過,主要是數據的接收
  2. 在和APP作對接開發的時候用到過,主要是文件數據的接收和保存

如何接收流文件並保存

/*
 * 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模擬發送流文件內容

/***
 * 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;
}

PHP經過文件流複製文件

/*
 * 複製文件流到文件中
 * @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;
}

PHP流的相關函數

擴展閱讀

相關文章
相關標籤/搜索