PHP 如何以文件形式輸出給前端


一般WEB大部分通訊都是依靠HTTP來傳輸,HTTP規定了信息的組成部分。

只要修改對應的返回HTTP頭,就能告訴客戶端返回的數據類型。

廢話不多說了,直接上代碼。

// 將路徑文件輸出給前端
$filePath = './test.jpg';
fileDownload($filePath);

// 將程序的輸出以文件形式輸出
//forceDownload('test.txt','你好呀');

/**
 * 將服務器上的文件輸出給前端
 *
 * @param $filePath
 * @return bool|false|int
 */
function fileDownload($filePath)
{
    if (false == file_exists($filePath)) {
        return false;
    }

    // http headers
    header('Content-Type: application-x/force-download');
    header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
    header('Content-length: ' . filesize($filePath));

    // for IE6
    if (false === strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6')) {
        header('Cache-Control: no-cache, must-revalidate');
    }
    header('Pragma: no-cache');

    // read file content and output
    return readfile($filePath);
}

/**
 * 將內容以文件形式輸出
 *
 * @param string $filename
 * @param string $data
 * @return bool
 */
function forceDownload($filename = '', $data = '')
{
    if ($filename == '' OR $data == '') {
        return false;
    }

    if (false === strpos($filename, '.')) {
        return false;
    }

    $mime = 'application/octet-stream';

    // 用戶使用是否IE
    if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== false) {
        $filename = rawurlencode($filename);
        header('Content-Type: "' . $mime . '"');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header("Content-Transfer-Encoding: binary");
        header('Pragma: public');
        header("Content-Length: " . strlen($data));
    } else {
        header('Content-Type: "' . $mime . '"');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header("Content-Transfer-Encoding: binary");
        header('Expires: 0');
        header('Pragma: no-cache');
        header("Content-Length: " . strlen($data));
    }

    exit($data);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM