php - How to force download of a file? - php

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?

You could try something like this:
<?php
// Locate.
$file_name = 'file.avi';
$file_url = 'http://www.myremoteserver.com/' . $file_name;
// Configure.
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$file_name."\"");
// Actual download.
readfile($file_url);
// Finally, just to be sure that remaining script does not output anything.
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.

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
Descargar

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.

<?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;
?>

I don't know this is the best way or not but I like that, short & simple.
If you want to download file when you visit URL, you can do like below
<a href="resume.pdf" download></a>
<script>document.querySelector('a').click();</script>

index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>download</title>
</head>
<body>
download
</body>
</html>
.htaccess
Options -Indexes
Options +FollowSymlinks
deny from all
download.php
$file = "pdf/teste.pdf";
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($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: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit();
}

<?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"

Related

change the name of the downloading file for the user downloading in php or html

Hi Is there is any way which i can give the user different name of the file which i have inside my server
for example i have file inside my server which has md5 name like
33e65007ba9387583d4902e5497fc9ac.mp3
i need when the user click to download this file to change the name of the downloading file to something.mp3
and this changing wanna be just with the user file downloading and it will not effect the name of the file in my server
More detail :
name of server file is :33e65007ba9387583d4902e5497fc9ac.mp3
name of the user file after downloading something.mp3 with
out changing server file
how can i do this thing ? with php ?
You could store file name in $name, and file content in $content. Then, use the following codes to download the file:
header('Content-Description: File Transfer');
header("Content-type: application/force-download");
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $name);
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: ' . strlen($content));
ob_clean();
flush();
echo $content;
i solved the problem by changing my download php file to
<?php
$file = $_GET['file'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>

Error in downloading file PHP

I have a link which shows the filename to download.When a user clicks it,it needs to get downloaded.The file gets downloaded but it contains only 0 KB.In console it shows
Resource interpreted as Document but transferred with MIME type application/force-download: "../download.php?file=filename"
My code is like this:
<a href="download.php?file=user_uploads/'.$_path['uploads'].
'logo_images/'.$row['FileName'].'" title="Click to download">'.$row['FileName'].'</a>
The download.php is like this:
<?php
$path = str_replace('/download.php?file=','',$_SERVER['REQUEST_URI']);
header("Content-Description: File Transfer");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"" . basename($path . $uri[1]) . "\"" );
#readfile($path);
?>
Thanks in advance.I have checked the path of the file also.
try
Click
download.php
<?php
$path = 'yourpath'.$_GET['file'];
header("Content-Description: File Transfer");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=".$_GET['file'] );
#readfile($path);
?>
file.txt - change with your file name
I had similar issue while downloading my file. I used this code for download.php:
<?php
$path = $_REQUEST['path'];
#setting headers
header('Content-Description: File Transfer');
header('Cache-Control: public');
header('Content-Type: application/zip');
header("Content-Transfer-Encoding: binary");
header('Content-Disposition: attachment; filename='. basename($path));
header('Content-Length: '.filesize($path));
ob_clean(); #THIS!
flush();
readfile($path);
exit;
?>
and my link was:
Download Pack
Hope it helps.

Php force Download - downloading corrupted file

Hi I am trying to allow download a demo file which is related to a product. my code is like this
if(isset($_POST['submit'])){
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/download/";
$path = $root.$path;
$filename = $demo;
$file = $path.$filename;
header('Content-Type: application/force-download');
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );
header("Content-Length: ".filesize($file));
readfile($file);
}
I am able to get file name which is associated with the product by
$demo
After user submits his information, download will start automatically. Now this is downloading a non existing file or corrupted file with the proper file name. please help
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($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: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
As you can see Content type is application/octet-steam meaning file is byte by byte encoded. Also the cache headers are set. Then headers are forcefully sent by ob_clean();flush(); and then the file is read.
The file_exists is there to ensure that given file exists. You should also try not not thrust user input as they could easy write names for your php codes and download EACH file. And with ../ in names of the files, even your documents or system files and so on.

PHP forced download going to webpage

I have an issue with the force download of a file.
I'm using PHPExcel to create a xls file based on information extracted from our database. This all works fine and the Excel file works as required.
I then attempt to force download of created file using the following function. However it downloads webpage rather than as a file.
Currently developing on Win XP SP3, Notepad++, XAMPP (Apache 2.4.3, PHP 5.4.7).
**function following
public function downloadfile($file){
if(file_exists($file) && is_file($file)){
//ob_start();
echo $file;
echo "in file exists";
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
//ob_end_flush();
}else
echo "file or location does not exist <br>";
echo $file;
}
Any help would be appreciated.
Thanks in advance
If its a excel file then just redirect to that url and by default it will ask for file download.
header("Location: http://site.com/path/to/file/filename.xlsx");
/* Make sure that code below does not get executed when we redirect. */
exit;
If in javascript give
location.href = 'http://site.com/path/to/file/filename.xlsx';
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
header("Content-Disposition: inline; filename=\"" . $fileName . ".xls\"");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filePath);
try this

txt file that I download is empty

The code below is for two purposes
1) I save a text file on my server in a folder named "backup_db" its working fine mean when I open that text file it contain all the data
2) At the same time i also make this file downloadable for a user so that he could download it for himself and could save it on his hard disk and according to my wish its downloading but unfortunately the .txt file saved on my hard disk is, when open its empty and i don't know why please help me out
//save file
$handle = fopen('backup_db/db-backup-'.date('d-m-Y_H-i-s').'-'.(md5(implode(',',$tables))).'.txt','w+');
$rr = fwrite($handle,$re);
//fclose($handle);
$ww = "db_backup".$rr.".txt";
//$handle = "";
header('Content-Disposition: attachment; filename=' . urlencode($ww));
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream');
header('Content-Type: application/download');
header('Content-Description: File Transfer');}}
You only set the HTTP header but did not write the file into the response body. Use either fpassthru() or readfile() to write the content of the file directly to the response.
Sample (taken from php.net)
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
flush();
readfile($file);
exit;
}
?>
BTW:
Settings the same header multiple times simply overwrites the value set before unless you set the second parameter of header() to false.
Your code
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream');
header('Content-Type: application/download');
results in the following header:
Content-Type: application/download
Sending a file namein the header just gives the user a suggested filename. Try echoing out the contents of the file.
You should add
header("Content-Length: $size")
where $size is size of yout file in bytes.
Check this
ex :
$filename = urlencode($fileName); //download.txt
header("Content-Disposition: attachment; filename=\"" . $filename. "\";" );

Categories