php - How to force download of a file?

2019-01-02 23:54发布

I'm looking to add a "Download this File" function below every video on one of my sites. I need to force the user to download the file, instead of just linking to it, since that begins playing a file in the browser sometimes. The problem is, the video files are stored on a separate server.

Any way I can force the download in PHP?

5条回答
做个烂人
2楼-- · 2019-01-03 00:21

Tested download.php file is

function _Download($f_location, $f_name){
  $file = uniqid() . '.pdf';

  file_put_contents($file,file_get_contents($f_location));

  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Length: ' . filesize($file));
  header('Content-Disposition: attachment; filename=' . basename($f_name));

  readfile($file);
}

_Download($_GET['file'], "file.pdf");

and the link to download is

<a href="download.php?file=http://url/file.pdf"> Descargar </a>
查看更多
太酷不给撩
3楼-- · 2019-01-03 00:23

Try this:

<?php
$FileName = '/var/ww/file.txt';
header('Content-disposition: attachment; filename="'.$FileName.'"');
readfile($FileName);

The key is the header(). You need to send the header along with the download and it will force the "Save File" dialog in the user's browser.

查看更多
不美不萌又怎样
4楼-- · 2019-01-03 00:26
<?php
$FileName = '/var/ww/file.txt';
header('Content-disposition: attachment; filename="'.$FileName.'"');
readfile($FileName);

using this code. is it possible to save the file name to what you want. for example you have url: http://remoteserver.com/file.mp3 instead of "file.mp3" can you use this script to download the file as "newname.mp3"

查看更多
三岁会撩人
5楼-- · 2019-01-03 00:34

You could try something like this:

$file_name = 'file.avi';
$file_url = 'http://www.myremoteserver.com/' . $file_name;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"".$file_name."\""); 
readfile($file_url);
exit;

I just tested it and it works for me.

Please note that for readfile to be able to read a remote url, you need to have your fopen_wrappers enabled.

查看更多
等我变得足够好
6楼-- · 2019-01-03 00:43
<?php

    $file_name = 'video.flv';
    $file_url = 'http://www.myserver.com/secretfilename.flv';
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"".$file_name."\""); 
    echo file_get_contents($file_url);
    die;

?>
查看更多
登录 后发表回答