如何在PHP中的下载链接? [关闭](how to make a download link i

2019-07-31 06:28发布

我可以使用SQL上载在数据库中的文件,但我怎样才能使一个下载链接呢? 就像当你在网上下载的东西,然后一个消息框将拿出你会问,如果你想用一个程序打开它或保存它。 我怎么能做到这一点在PHP? 你能给我为它的代码? 我还是个菜鸟。

Answer 1:

将这个代码的网页(与PHP代码从DB获得的信息,并将其放置在名称/大小/数据变量一起上,然后链接到该页面。

<?php
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $name_of_file);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size_of_file);

echo $file_data;
?>

不是所有上面列出的标题是绝对必要的-事实上,只有Content-Type头是真正需要做的下载正常工作。 内容处理标头是好事,包括让你可以指定一个合适的文件名; 别人只是帮助浏览器处理下载的更好,如果你的愿望可以省略。



Answer 2:

一些编辑此代码,使之在我的情况下工作。 - 对于MP3音乐

你可以通过调用该文件称这种filedownload.php -把它放在你的服务器。

在这个例子中从WordPress的自定义字段 - 从一个文件中像说它

<a href="<?php bloginfo('url'); ?>/filedownload.php?download=<?php echo get_post_meta($post->ID, 'mymp3_value', true) ?>">MP3</a>

很简单的事情。

<?php
    $name_of_file = $_GET["download"];

    header('Content-Description: File Transfer');
    // We'll be outputting a MP3
    header('Content-type: application/mp3');
    // It will be called file.mp3
    header('Content-Disposition: attachment; filename=' .$name_of_file);
    header('Content-Length: '.filesize($name_of_file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    // The MP3 source is in somefile.pdf
    //readfile("somefile.mp3");

    readfile_chunked($name_of_file);

    function readfile_chunked($filename) { 
        $chunksize = 1*(1024*1024); // how many bytes per chunk 
        $buffer = ''; 
        $handle = fopen($filename, 'rb');

        if ($handle === false) { 
            return false; 
        } 

        while (!feof($handle)) { 
            $buffer = fread($handle, $chunksize); 
            print $buffer; 
        } 

        return fclose($handle); 
    } 
?>


文章来源: how to make a download link in PHP? [closed]