Renaming Download File Using Header in PHP - php

i have a link pointing to a music file on my site, now the name of the file was hashed when it was uploaded so i want to use the original filename which i have stored in my database, I did some research and found this new 'download' attribute for the 'a' tag but that only works in later versions of firefox and chrome, it doesn't work in ie and also doesn't work with the download manager i use so i checked online and found out about headers which i then implemented. I now get the filename changed allright but the music file keeps on getting saved as a '11.35kb' filesize no matter the music file i try to download. This is my code:
if (isset($_REQUEST['download']))
{
$download_id = $_REQUEST['download'];
$db = new MysqliDatabase(ConnectionString);
$result = array();
$result = $db->query_one("SELECT TrackID, ma.ArtisteName, FeaturedArtistes,
mc.Category, TrackName
FROM `musictracks` mt
LEFT JOIN `musiccategories` mc
ON mt.CategoryID = mc.CategoryID
LEFT JOIN `musicartistes` ma
ON mt.ArtisteID = ma.ArtisteID
WHERE mt.TrackID = '$download_id';");
$filename = $result->TrackPath;
$outputfilename = $result->ArtisteName . ' ft. ' . $result->FeaturedArtistes . ' - ' . $result->TrackName . '.mp3';
header("Content-Type: audio/mpeg");
header("Content-Disposition: attachment; filename=\"" . basename($outputfilename) . "\";" );
header("Content-Transfer-Encoding: binary");
readfile("$filename");
}
And this is the download link:
<a href="<?php echo 'musicdownload.php?download='. $row->TrackID ?>" ><img src="images/download.png" alt="download" title="download" width="14" height="14" /></a>

My PHP is a bit rusty but I can think of one thing with your code, no content length header. Update your code to this and see if that works:
if (isset($_REQUEST['download'])) {
{
$download_id = $_REQUEST['download'];
// ...
$filename = $result->TrackPath;
$outputfilename = $result->ArtisteName . ' ft. ' . $result->FeaturedArtistes . ' - ' . $result->TrackName . '.mp3';
if (file_exists($filename)) {
header("Content-Type: audio/mpeg");
header("Content-Disposition: attachment; filename=\"" . basename($outputfilename) . "\";" );
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($filename));
ob_clean();
flush();
readfile($filename);
exit;
}
}
}
Note that we use flush(); to send the headers to the browser before we start downloading the actual file. And I also added an if (file_exists($filename)) to make sure we have a file to send. I'd recommend you put an else clause there to give you something that will show you if you don't have a file like you expect...

header("Content-Type: application/force-download");
header("Content-Type:audio/mpeg");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=".$file_name);

Please download your mp3 files using curl
Here is sample code for your reference
<?php
if(isset($_REQUEST['inputurl']) && $_REQUEST['inputurl']!="") {
$file = $_REQUEST['inputurl'];
header("Content-type: application/x-file-to-save");
header("Content-Disposition: attachment; filename=".basename($file));
readfile($file);
}
?>
<form name="from" method="post" action="">
<input name="inputurl" type="text" id="inputurl" value="" />
<input type="submit" name="Button1" value="Get File" id="Button1" />
</form>
may be it will help you.

Related

Failed to load PDF document in my PHP code

I am new to PHP and trying to implement below functionality through code give
Functionality:
I have one Download button and upon clicking i should be able to download my .pdf file stored under htdocs-->xxfilename-->abc.pdf;
Code:
I am using below code in my xyz.php web page
<?php
$title = "Learning";
$content = '
<h3> Intro</h3>
<p>
Introduction goes here
</p>
<form action = "xyz.php" method = "post" name = "downloadform">
<input type="submit" value="Download" name="dwnld_file"/>
</form>
';
if (isset($_POST['dwnld_file'])) {
mysql_connect("localhost", "root", "");
mysql_select_db("PQR");
$res = mysql_query("Select * from tab1");
while ($row = mysql_fetch_array($res)) {
$file = '$row["col2"]';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $row["col2"] . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Content-Length:' . filesize($file));
readfile($file);
}
}
include 'Template.php';
?>
Error:
My pdf file is getting downloaded but upon opening it it says "failed to load pdf document"
Please help where i am wrong.
***Edit****
I tried different approach and my file is downloading but still it says "failed to load pdf document"
My other approach code is below
<form action = "xyz.php" method = "post" name = "downloadform">
<input type="submit" value="Download " name="dwnld_file"/>
</form>
<?php
if (isset($_POST['dwnld_file'])) {
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$res = mysql_query("Select * from tab1");
while ($row = mysql_fetch_array($res)) {
$file = $row["col1"];
echo $file;
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' .$file. '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Content-Length:' . filesize($file));
readfile('myfile/'.$file);
}
}
?>
Please tell me if i am doing anything wrong.
I implemented another solution after doing some more study and i was able to solve the problem.
Below is my code i used to implement.
Concept:
1) We can use HTML+JSP+PHP to get this functionality.
2) At HTML + JSP side we need to call eventListener to capture the event of clicking the button.
3) This event will redirect to the php page which will download the pdf file to your local computer.
Code Snippet:(here XYZ is the name of page where you want to show Download button)
in XYZ.php
<input type="button" id="btnshow" value="Download" name="dwnld" />
<script>
var btn = document.getElementById('btnshow');
btn.addEventListener('click', function () {
document.location.href = '<?php echo 'download.php'; ?>'
})
</script>
in download.php
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("database_name");
$res = mysql_query("Select * from table_name");
while ($row = mysql_fetch_array($res)) {
$file = 'Pdf_File/' . $row["Path"];
$filename = $row["Path"];
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
readfile($file);
}
?>
Hope it help some one out there newbie like me.
Happy Coding!

PHP : Force PDF file to download

i am trying to download a .pdf file on button submit, following is my code
if(mail('myemail#gmail.com', 'Brochure Downloaded ', $string)){
$text= 'Your message recieved, We will contact you shrtly ';
$file_url = 'http://www.website.com/brochure.pdf';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url); // do the double-download-dance (dirty but worky)
}
Now whats happening is that email is sent but files is not downloaded, instead page gets reloading and long characters are printed on the screen ,
Need your help with this please
this is what i get
I have changed headers a little bit. I think the proper content type is application/pdf andsome of headers are not necessery.
if(mail('myemail#gmail.com', 'Brochure Downloaded ', $string)){
$text= 'Your message recieved, We will contact you shrtly ';
$file_url = 'http://www.website.com/brochure.pdf';
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='" . basename($file_url) . "'");
readfile($file_url); // do the double-download-dance (dirty but worky)
}
You may also add the content length:
header('Content-Length: ' . filesize($file_url));
check this code, first you need to add content type if you download any type file as like if you want to download image then
header('Content-Type: image/png'); if pdf then
header("Content-Type: application/pdf"); etc
<?php
if (mail('myemail#gmail.com', 'Brochure Downloaded ', $string)) {
$text = 'Your message recieved, We will contact you shrtly ';
$file_url = 'http://www.website.com/brochure.pdf';
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file_url");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
readfile($file);
}
?>
you may use
header('Content-Length: ' . filesize($file_url));
you should use Content-Length if you want someone download a file with another header

How to remove the tmp- from my download name

So when a user downloads a file I currently have it pull the song name through something that looks like this.
$songs = file_get_contents('https://api.soundcloud.com/tracks/'.$id.'/stream?client_id='.$myID.'');
$filename = './tmp/' . stripslashes(htmlspecialchars($songTitle)) . '.mp3';
$filenames = '/tmp/' . stripslashes(htmlspecialchars($songTitle)) . '.mp3';
$trying = '' . stripslashes(htmlspecialchars($songTitle)) . '';
$songname = stripslashes(htmlspecialchars($songTitle));
file_put_contents($filename, $songs);
<form method="POST" action="http://example.com/download.php" accept-charset="utf-8">
<input type="hidden" name="file_name" value="<?php print $trying; ?>" />
<input type="hidden" name="song_name" value="<?php print $songname; ?>" />
<input type="Submit" class="btn btn-success" value="Download Song" />
</form>
Then within the download.php file I have the following.
$file = 'tmp/' . $_POST['file_name'] . '.mp3';
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.$file);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
header("Content-Type: audio/mp3");
readfile($file);
How ever when a user downloads a file it brings up something that looks like this tmp-song-artist-song-name.mp3 any help is very appreciated!
Edit:
Preview Image
This is what happens when I change the header('Content-Disposition: attachment; filename='.$file); line to header('Content-Disposition: attachment; filename='.$songtitle);
$songtitle = $_POST['song_name'];
It seems to fix the title issue but creates an entirely new issue which is not what we want.
You are using wrong Content-Disposition header. In your first post you have used full file name alongwith tmp/ and after editing you missded .mp3 at end. I have corrected your download file code below:
$file = 'tmp/' . $_POST['file_name'] . '.mp3';
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.$_POST['file_name'] . '.mp3');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
header("Content-Type: audio/mp3");
readfile($file);
Remove 'tmp/' section from file name.
header('Content-Disposition: attachment; filename=' . str_replace('tmp/', '', $file));

How can I add a download button?

I have this code which outputs a QR code:
<?php
include(JPATH_LIBRARIES . '/phpqrcode/qrlib.php');
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('Soci', 'Nom', 'Cognoms', 'eCorreu')))
->from($db->quoteName('#__rsform_socis'))
->where($db->quoteName('username') . ' = '. $db->quote($user->username));
$db->setQuery($query);
$codeContents = $db->loadObjectList();
$data .= "Soci NÂș: {$codeContents[0]->Soci}\n ";
$data .= "Nom: {$codeContents[0]->Nom} ";
$data .= "{$codeContents[0]->Cognoms}\n";
$data .= "e-correu: {$codeContents[0]->eCorreu}";
$tempDir = JPATH_SITE . '/images/';
$fileName = 'qr_'.md5($data).'.png';
$pngAbsoluteFilePath = $tempDir.$fileName;
$urlRelativeFilePath = JUri::root() .'images/' . $fileName;
if (!file_exists($pngAbsoluteFilePath)) {
QRcode::png($data, $pngAbsoluteFilePath);
}
echo '<img src="'.$urlRelativeFilePath.'" />';
?>
How can I add a download button so the user can download the code to the computer?
Thanks,
Dani
This is more of a HTML question, so lets get started: There is an attribute called "download" and you can use it like this:
echo 'Download QR';
It downloads the file as the name you supply here. So if the image url on your server is: wadAHEybwdYRfaedBFD22324Dsefmsf.png it would download the file as "qrcode.png". Unfortunately this is not supported in all browsers. Another easy fix is to make a form that has your filename as an action like so:
echo '<form method="get" action="'.$urlRelativeFilePath.'"><button type="submit">Download QR Code!</button></form>';
Another way (little more code) to do this is using PHP with some specific headers like this:
<?php
// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/path2file/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
// example: place this kind of link into the document where the file download is offered:
// Download here
?>
It works for large and small files and also for many different filetypes. Info found here: http://www.finalwebsites.com/forums/topic/php-file-download
Well, you are obviously creating a .png picture file of the QR code with your script. So simply add a link to the location of the picture:
echo "Download";
This will however just redirect the user to the picture in his browser.
If you want to force a download you will need to use PHP headers to send the file to the visitors browser.
For example make a script and call it download_code.php.
Then add:
echo "Download";
And in the download_code.php:
$handle = fopen("/var/www/yourdomain.com/images/" . $filename, "r");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
header('Content-Length: ' . filesize("/var/www/yourdomain.com/images" . $filename));
flush();
readfile("/var/www/yourdomain.com/images" . $filename);
fclose($handle);

cannot open downloaded file having '&' symbol in filename

I want to download files uploaded to the server.I have the filenames as links and I need to download the file directly when the user click it.I have succeeded in that.The issue now I face is I cant open the files containing amp symbols in their filename,eventhough it is downloaded. eg: &,test.doc(filename containing other special symbols can be downloaded and opened properly.)
My php script is like this:
<script>
function downloadme(file){
var link = "download.php?file=" + file;
location.replace(link);
}
</script>
<a title="Click to download" href="javascript:downloadme()">filename</a>
download.php
<?php
$path = $_GET['file'];
header("Content-Description: File Transfer");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"" . basename($path . $uri[1]) . "\"" );
#readfile($path);
?>
Here's what I did
download.php:
<?php
$path = $_GET['file'];
header("Content-Description: File Transfer");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"" . basename($path . $uri[1]) . "\"" );
#readfile($_GET['file']);
?>
html file:
<script>
function downloadme(file){
var link = "download.php?file=" + escape(file);
location.replace(link);
}
</script>
<a title="Click to download" href="javascript:downloadme('test&12.doc')">filename</a>

Categories