如何强制下载PHP?

时间:2013-07-08 09:20:30

标签: php download

此脚本不断返回“else”响应。为什么我的病情会继续失败:

<?php

    $fileName = $_GET['far_sighted_michael_pitluk.mp3'];
    $fileDisplayName = "Far-Sighted";

    // Fetch the file info.
    $filePath = 'http://michaelpitluk.com/audio/far_sighted_michael_pitluk.mp3';

    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileDisplayName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
?>

我不明白路径有什么问题。

2 个答案:

答案 0 :(得分:0)

fileexist()函数获取主机上文件的路径,而不是完整的URL 试试这个

$filePath = 'audio/far_sighted_michael_pitluk.mp3';

答案 1 :(得分:0)

如果您的$filePathhttp://开头,则可能需要启用allow_url_fopenPHP Manual

尝试

ini_set("allow-url-fopen", true);
// Fetch the file info.
$filePath = 'http://michaelpitluk.com/audio/far_sighted_michael_pitluk.mp3';

编辑: 试试这个:

<?php

    $fileName = $_GET['far_sighted_michael_pitluk.mp3'];
    $fileDisplayName = "Far-Sighted.mp3";

    // Fetch the file info.
    $filePath = '../audio/far_sighted_michael_pitluk.mp3';

    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileDisplayName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
?>