I want to force download a pdf,doc or docx file.
With the following code,Pdf files get opened in my tab instead of getting downloaded.
I have a table having download link in every row.I want to download file on click of this link.
foreach($a as $id = > $item) {
echo '<tr><td><a href="http://staging.experiencecommerce.com/ecsite-v3/uploads/'.substr($item['f_resume'], 63).'" ">';
//Note:substr($item['f_resume'], 63) is file_name
echo '</a></td><td>'.$item['f_date'].'</td></tr>';
}
I went through some Question on SO with same problem and tried their solution,but in Vain.
When I included the solution inside foreach,the page downloads file on load and when I place the solution outside ,the Php script gets downloaded.
Where am I going wrong?
You can set headers that will force downloading:
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="filenamehere.pdf"');
If you're not using PHP to provide content of that files you can set headers using eg. .htaccess (requires mod_headers).
<FilesMatch ".pdf$">
FileETag None
<ifModule mod_headers.c>
Header set Content-Type "application/force-download"
</ifModule>
</FilesMatch>
After our whole chat session I think we can leave this answer here, just for future reference:
As seen in your initial post, once you click the link, you relinquish all control to the browser so it will treat the file as it sees fit. Usually this involves trying to find whatever application or plugin the system can find to treat your file.
Whenever you want to force the download of the file all you have to do is divorce the presentation itself from the task at hand. In this particular case:
1 - Create a new script that will identify the file via parameters passed and force the download on it, as seen on the examples at this site php.net/manual/en/function.readfile.php.
2 - Rework the presentation so the links do no longer point to the file itself, but to the new script with the appropriate parameters (like, for example, download_file.php?file_id=#FILE_ID#).
3 - Treat the case in which the file can not be found by, for example, die("The file could not be found") before setting the headers.
One word of advice: do not use the file location as a parameter!!!. Use instead something that you can retrieve from a database to then collect the file location. If you pass the file location itself as a parameter nothing is stopping me from doing this:
http://yoursite.com/download_file.php?file=download_file.php
http://yoursite.com/download_file.php?file=index.php
http://yoursite.com/download_file.php?file=whatever_file_there_is
With the adequate circumstances, like autodetection of the xtype for the requested file, it would allow me to access your code and exploit any possible flaws
One second and final note of advice: php can only output one thing at once. If you want it to output a website you can't output a pdf file afterwards. That's why - among other reasons - you divorce the different tasks at hand and also, that's why everything went awry when you tried directly including the download script after each link was printed.
If it helps, imagine php not as your usual real-time programming language, but as a printer. It will print everything you tell it to and serve it in reasonably sized chunks. There's no stopping it until the end is reached, there's no possible exploring two opposite branching code paths unless you call the script again with the appropriate conditions.
Hope the chat helped you.
Related
I have a PHP application that generates a CSV file and redirect the user to a static page linking to the file, just the example below :
https://www.example.com/public_html/static/temp/myfile.csv
Problem is, Chrome is opening the file instead of saving it. I need Chrome to save this file, as it would do with any other file like a zip or mp3, for instance.
Here is what I tried :
header('location:https://www.example.com/public_html/static/temp/myfile.csv');
header('Content-Disposition: attachment; filename=myfile.csv');
But no luck, Chrome keeps showing the myfile.csv contents instead of downloading it.
Any ideas ?
Thanks
Your argumentation in the comments has one never-ending misunderstanding: the Location header instructs any client to perform a new request to the given URI. With that the current request is over. Headers from the current request (i.e. Content-Disposition) aren't magically carried over to the next request.
In other words: your "static page linking to the file, just the example below" must send your wanted header.
Ultimately I'm sure it's not a Chrome problem either, but affects all internet browsers, as they easily detect the CSV data as text, hence being able to render/display that data instead of only being able to save it to a file.
With html5 you can set the "download" attr in an element.
Download it!
Source : http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download
After struggling with this issue for some days, the only real solution i got is to ZIP the file and then redirecting to the ZIP file instead of the CSV. By doing this, Chrome will download the ZIP file instead of opening it :
header('location:https://www.example.com/public_html/static/temp/myfile.csv.zip');
I am trying to generate an archive on-the-fly in PHP and send it to the user immediately (without saving it). I figured that there would be no need to create a file on disk as the data I'm sending isn't persistent anyway, however, upon searching the web, I couldn't find out how. I also don't care about the file format.
So, the question is:
Is it possible to create and manipulate a file archive in memory within a php script without creating a tempfile along the way?
I had the same problem but finally found a somewhat obscure solution and decided to share it here.
I came accross the great zip.lib.php/unzip.lib.php scripts which come with phpmyadmin and are located in the "libraries" directory.
Using zip.lib.php worked as a charm for me:
require_once(LIBS_DIR . 'zip.lib.php');
...
//create the zip
$zip = new zipfile();
//add files to the zip, passing file contents, not actual files
$zip->addFile($file_content, $file_name);
...
//prepare the proper content type
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=my_archive.zip");
header("Content-Description: Files of an applicant");
//get the zip content and send it back to the browser
echo $zip->file();
This script allows downloading of a zip, without the need of having the files as real files or saving the zip itself as a file.
It is a shame that this functionality is not part of a more generic PHP library.
Here is a link to the zip.lib.php file from the phpmyadmin source:
https://github.com/phpmyadmin/phpmyadmin/blob/RELEASE_4_5_5_1/libraries/zip.lib.php
UPDATE:
Make sure you remove the following check from the beginning of zip.lib.php as otherwise the script just terminates:
if (! defined('PHPMYADMIN')) {
exit;
}
UPDATE:
This code is available on the CodeIgniter project as well:
https://github.com/patricksavalle/CodeIgniter/blob/439ac3a87a448ae6c2cbae0890c9f672efcae32d/system/helpers/zip_helper.php
what are you using to generate the archive? You might be able to use the stream php://temp or php://memory to read and write to/from the archive.
See http://php.net/manual/en/wrappers.php.php
Regarding your comment that php://temp works for you except when you close it, try keeping it open, flushing the output, then rewind it back to 0 and read it.
Look here for more examples: http://us.php.net/manual/en/function.tmpfile.php
Also research output buffering and capturing: http://us.php.net/manual/en/function.ob-start.php
You need to use ZipArchive::addFromString - if you use addFile() the file is not actually added until you go to close it. (Horrible bug IMHO, what if you are trying to move files into a zip and you delete them before you close the zip...)
The addFromString() method adds it to the archive immediately.
Is there really a performance issue here, or does it just offend your sense of rightness? A lot of processes write temporary files and delete them, and often they never hit the disk due to caching.
A tempfile is automatically deleted when closed. That's it's nature.
There are only two ways I can think of to create a zip file in memory and serve it and both are probably more trouble than they are worth.
use a ram disk.
modify the ziparchive class to add a method that does everything the close() method does, except actually close the file. (Or add a leave-open parameter to close()).
This might not even be possible depending on the underlying C libraries.
So this is simple to understand what i want to achieve. So i get links like theese:
http://rockdizfile.com/atfmzkm7236t
http://rockdizfile.com/xuj5oincoqmy
http://rockdizfile.com/pg8wg9ej3pou
So theese links are from one cloud storage site I want to make a php script that automates their downloading.
So I can't find which is the script or the thing these links download button starts and how can I start that so i can download it with php on my server?
Basically my idea is to download a lot of files but don't wanna do it manually so need automatic way of doing it. As far as I know I make a request which is the following 2 urls:
http://rockdizfile.com/pg8wg9ej3pou
http://wi32.rockdizfile.com/d/wsli6rbhfp4r2ge4t7cqeeztijrprelfiw4afvqg5iwspmvqabpkmgiz/Desislava%20feat.%20Mandi%20&%20Ustata%20-%20Pusni%20go%20pak%20(CDRIP).mp3
So the first url is executing the next one but here comes the tricky part as far as I tested that last string Desislava%20feat.%20Mandi%20&%20Ustata%20-%20Pusni%20go%20pak%20(CDRIP).mp3 is the file name we get when downloading so if you change it with for example somefile.mp3 it will download somefile.mp3 but with the same file content as http://wi32.rockdizfile.com/d/wsli6rbhfp4r2ge4t7cqeeztijrprelfiw4afvqg5iwspmvqabpkmgiz/Desislava%20feat.%20Mandi%20&%20Ustata%20-%20Pusni%20go%20pak%20(CDRIP).mp3 so the data is hidden in this hash wsli6rbhfp4r2ge4t7cqeeztijrprelfiw4afvqg5iwspmvqabpkmgiz or i think so. And now is the tricky part how to get this hash? we have almost everything we have the code for the url atfmzkm7236t the hash wsli6rbhfp4r2ge4t7cqeeztijrprelfiw4afvqg5iwspmvqabpkmgiz and the filename Desislava%20feat.%20Mandi%20&%20Ustata%20-%20Pusni%20go%20pak%20(CDRIP).mp3 There must be a way to download from this site without clicking so please help me kinda a hack this :)
you can use PHP's header function to force a file to download
header('Content-disposition: attachment; filename=index.php');
readfile('Link');
You should know that this will not give you the ability to download PHP files from external websites.
You can only use this if you got the direct link to a file
It's impossibly to tell you without the source code
e.g. sha1("Test Message") gives you 35ee8386410d41d14b3f779fc95f4695f4851682 but sha256("Vote this up") gives you 65e03c456bcc3d71dde6b28d441f5a933f6f0eaf6222e578612f2982759378ed
totally different... unless you're hidden function add's "65e03c456bcc3d71dde6b28dxxxxxxxxxxxxxxxxxxxxxxxxxx" (where xxxxxxxxxxxxxxxxxxxxxxxxxx is a bunch of numbers I can't be arsed to work out) to each hash...
then sha1("Test Message") gives you 65e03c456bcc3d71dde6b28d441f5a933f6f0eaf6222e578612f2982759378ed
The file is embedded into the swf player.
alert(jwplayer('mp3player').config.file);
Something like:
<?PHP echo file_get_contents($_GET["url"]); ?>
<script>
document.location=jwplayer('mp3player').config.file;
</script>
Though I've actually just noticed they change 5 digits of the URL on each page request, and the script above uses 2 page requests. One to get the URL and HTML source and another to try and download the file, meaning the URL has changed before the second request has started.
I'm generating a pdf file with html2fpdf.
$pdf = new HTML2FPDF();
$pdf->HTML2FPDF("P","mm","A4");
$pdf->AddPage();
$pdf->WriteHTML($html);
$pdf->output('sample.pdf');
This sample works great. But:
How do I delete the pdf after the output? I just want to have links in my tool, the users can download the pdf and after that it shoud be deleted on the server.
How can I 'clean up' after generating the pdf?
You can use PHP's file deletion function called unlink()
Call this function with the full path to the generated PDF file (or any file for that matter) and PHP will delete that file.
http://php.net/manual/en/function.unlink.php
You don't necessarily have to delete the file immediately after the user has downloaded it. You can just as easily place all the generated files in one central folder and have a cron job execute a more general clean up script simply removing the older files.
One method could be -
Scan the contents of the folder using scandir().
Iterate over its files in a foreach loop..
Inspect the creation time of each file using filemtime().
If the creation time was over hour ago, delete the file using unlink().
Because you are generating the PDF file yourself within your PHP code, I didn't mention the permissions consideration. Here would be a good place to mention that your PHP must have the correct file system permissions in order to perform any action on the file system. You are creating a PDF file so it's safe to assume that you have the correct permissions to make changes to the file system but if you plan on using this unlink() function in other scripts make sure that the files you are dealing with have the correct permissions set.
If you don't add the 'F' flag to the output function there will be no pdf files stored on the server at all:
$pdf->output('sample.pdf', 'F'); //stores PDF on server
In your case the script itself behaves like an actual pdf file. So, creating a link to the script is just like a link to the pdf, except that the PDF is created every time the script is requested. To tell the browser it's a PDF the content-type response header must be set to application/pdf:
content-type: application/pdf
This way the broser knows that it's a pdf even if the URL is ending in a .php. You can use rewrite engine to make it end in pdf or whatever else.
Sending the headers is done by the fpdf/tcpdf. In short: you don't have to do any cleanup, because no pdf file is stored on the server.
If you wonder what the name is for than, try saving the pdf file. The recommanded name when saving will be sample.pdf.
Reference:
PHP header() function, at the examples there is one for sending pdf
FPDF::Output()
TCPDF::Output()
I am trying to generate an archive on-the-fly in PHP and send it to the user immediately (without saving it). I figured that there would be no need to create a file on disk as the data I'm sending isn't persistent anyway, however, upon searching the web, I couldn't find out how. I also don't care about the file format.
So, the question is:
Is it possible to create and manipulate a file archive in memory within a php script without creating a tempfile along the way?
I had the same problem but finally found a somewhat obscure solution and decided to share it here.
I came accross the great zip.lib.php/unzip.lib.php scripts which come with phpmyadmin and are located in the "libraries" directory.
Using zip.lib.php worked as a charm for me:
require_once(LIBS_DIR . 'zip.lib.php');
...
//create the zip
$zip = new zipfile();
//add files to the zip, passing file contents, not actual files
$zip->addFile($file_content, $file_name);
...
//prepare the proper content type
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=my_archive.zip");
header("Content-Description: Files of an applicant");
//get the zip content and send it back to the browser
echo $zip->file();
This script allows downloading of a zip, without the need of having the files as real files or saving the zip itself as a file.
It is a shame that this functionality is not part of a more generic PHP library.
Here is a link to the zip.lib.php file from the phpmyadmin source:
https://github.com/phpmyadmin/phpmyadmin/blob/RELEASE_4_5_5_1/libraries/zip.lib.php
UPDATE:
Make sure you remove the following check from the beginning of zip.lib.php as otherwise the script just terminates:
if (! defined('PHPMYADMIN')) {
exit;
}
UPDATE:
This code is available on the CodeIgniter project as well:
https://github.com/patricksavalle/CodeIgniter/blob/439ac3a87a448ae6c2cbae0890c9f672efcae32d/system/helpers/zip_helper.php
what are you using to generate the archive? You might be able to use the stream php://temp or php://memory to read and write to/from the archive.
See http://php.net/manual/en/wrappers.php.php
Regarding your comment that php://temp works for you except when you close it, try keeping it open, flushing the output, then rewind it back to 0 and read it.
Look here for more examples: http://us.php.net/manual/en/function.tmpfile.php
Also research output buffering and capturing: http://us.php.net/manual/en/function.ob-start.php
You need to use ZipArchive::addFromString - if you use addFile() the file is not actually added until you go to close it. (Horrible bug IMHO, what if you are trying to move files into a zip and you delete them before you close the zip...)
The addFromString() method adds it to the archive immediately.
Is there really a performance issue here, or does it just offend your sense of rightness? A lot of processes write temporary files and delete them, and often they never hit the disk due to caching.
A tempfile is automatically deleted when closed. That's it's nature.
There are only two ways I can think of to create a zip file in memory and serve it and both are probably more trouble than they are worth.
use a ram disk.
modify the ziparchive class to add a method that does everything the close() method does, except actually close the file. (Or add a leave-open parameter to close()).
This might not even be possible depending on the underlying C libraries.