file downloading through headers - php

All i need help in downloading a file through headers its working fine but the problem is that the file is place in a folder and i don't understand how to give path for that specific file. the file downloads always give me empty file. My basic sanario is that i click a link(image) for download a file on page named(documents.php) which send me to the other page named download.php.in that page i set header for downloading the clicked file like
this is a link (document.php)
<img src="images/xl_icn.jpg" alt="" width="19" height="20" />
this is header(download.php)
header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header("Content-Disposition: attachment; filename='".$_GET['title']."'");
if(isset($_SESSION)){
header('Location: documents.php');
}
and after downloading it send me back to the documents.php page but the files which i want to download is in folder uploads/documents and i dont know how to download that files placed in uploads/documents.

You have a good start I would modify your code to be more like the following:
$path = $_SERVER['DOCUMENT_ROOT']."/uploads/documents/";
$fullPath = $path.$_GET['title'];
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header("Content-Disposition: attachment; filename='".$_GET['title']."'");
header("Content-length: $fsize");
header("Cache-control: private");
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
$path you would update for what folder
The if statement works the required file calls and echos the page content in a buffer style.
This can be further expanded to include a switch statement depending on extensions to change the Content-type declaration. Since you will buffer the content to the page, you cannot call header("Location");. Or you will get "header cannot be sent since page content has loaded" due to the buffering.
I would suggest opening it in a new window or a iframe (wrapped in a div and could be hidden) on the page. You could also include it in the document.php file as well instead of calling a separate file.

You can't redirect from the download page back. download.php should just do
echo $binary_file_contents;
and exit, it can't send redirect headers.
You can open it in an iframe, and that way you will not actually leave the documents.php page

Related

Download PHP/HTML/CSS to PDF Document

Here I have some code, it does as it says and downloads, however only downloads a white blank empty file, and I am trying to use this one Wordpress and must be without a plugin. The script works, but its not downloading any information onto the PDF document, its just a white blank page here is the code, looking for a solution to added Wordpress post to the document, here is the link and the code, ideally I want it to download the page in which the link is executed.
HTML Link
Download file
download.php
<?php
ignore_user_abort(true);
$path = ""; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\].]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$fullPath = $path.$dl_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");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
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;
?>
DO NOT USE THE CODE ABOVE!
It not only doesn't convert anything into PDF but also allows the world to download arbitrary files readable by the webserver as plaintext. So one could download your mysql database credentials or your FTP password if set in wp-config.php.
Explanation: the code doesn't convert anything. It just takes the content of an arbitrary file and outputs it with a PDF or octet-stream content type. Take a text editor and look at the "PDF" you downloaded.
It looks like you haven't to set the line
$path = ""; // change the path to fit your websites document structure to the full path pointing to some_file.pdf.

Download a PowerPoint just created in PHP

I am trying to add the PHPPowerPoint to one of my tools. I add all the file that PHPPowerPoint needs and write the download link to the right page but when I try to download it, it say to me that I don't have the permit to access to the file.
I tried to change the permit manually but nothing change, also beacuse everytime PHP create a new file with the default permit.
I tried to use chmod on it but nothing change.
I tried also chgrp and chown to change the owner (that is "daemon").
It's weird because when I use it out from the tool, with only the code to create the PP file everything works also with this permit.
The tool where I want to add the PP file download was coded with codeigniter.
Here's how to write a PHPPowerPoint object to the browser and have the user download it. It doesn't ever write to the file system, so there's no need for write permissions.
$ppp = new PHPPowerPoint;
// create the powerpoint, adding slides, content, etc.
// ...
// done
// set up the writer
$pppwriter = PHPPowerPoint_IOFactory::createWriter($ppp, 'PowerPoint2007');
// tell the browser a powerpoint is coming
header('Content-Type: application/vnd.openxmlformats-officedocument.presentationml.presentation; charset=binary');
// make sure it downloads as $filename
header("Content-Disposition: attachment; filename={$filename}");
// output the powerpoint file data
$pppwriter->save('php://output');
you can use the download helper
The Download Helper lets you download data to your desktop.
Loading this Helper
This helper is loaded using the following code:
$this->load->helper('download');
The following functions are available:
force_download('filename', 'data')
Generates server headers which force data to be downloaded to your desktop. Useful with file downloads. The first parameter is the name you want the downloaded file to be named, the second parameter is the file data. Example:
$data = 'Here is some text!';
$name = 'mytext.txt';
force_download($name, $data);
If you want to download an existing file from your server you'll need to read the file into a string:
$data = file_get_contents("/path/to/photo.jpg"); // Read the file's contents
$name = 'myphoto.jpg';
force_download($name, $data);
I done the functionality for downloading .pdf file as it is in core php,
Here is a sample code for it
$path = "path of your file";
$fullPath = $path.$_GET['fnm'];
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;
Just change file extension pdf to ppt(wherever pdf extension occurs).

how to download a file from file_get_contents?

I want to get a file via file_get_contents to copy and rename it and then trigger the download. In other words, a user click a link to a controller, the controller does the business and then return the new file to download.
All fine, the only thing I can't do till now is rename and force donwload of the file.
You can change the headers and echo out the file:
// Download the file
header('Content-Disposition: attachment; filename="myfile.csv"');
header("Content-Type: text/csv");
header("Content-Length: " . filesize($outputName));
echo (file_get_contents($outputName));
unlink($outputName);

How to Stop Header, so I can echo to screen from the same function (PHP)

I'm finding Headers a nightmare to get my head around, I have a file the user downloads which works fine. However I then whish to echo to the screen that xx file has been sent; but ofc this echo is just placed inside the sent file.
Full dowload code is as follows:
function download()
{
$orderNo = $_POST['orderNo'];
$lines = file('F:/xamptest/htdocs/UniProject/upload/Amazon output.txt');
$lineCount = count($lines);
if($orderNo>0&&$orderNo<=$lineCount)
{
$lineEx = explode("\t", $lines[($orderNo-1)]);
$file = fopen('Order.txt', 'w');
fwrite($file, $lineEx[8].PHP_EOL .$lineEx[17].PHP_EOL .$lineEx[18].PHP_EOL .$lineEx[19].PHP_EOL .$lineEx[20].PHP_EOL .$lineEx[21].PHP_EOL .$lineEx[22].PHP_EOL .$lineEx[23].PHP_EOL);
fclose($file);
$file = 'Order.txt';
ob_end_clean();
header("Cache-Control: private");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
echo "Current order, number: ".$orderNo."<br> Has been downloaded";
}
else
{
echo "Please enter a valid Order Number between 1 and ".$lineCount;
}
}
I can't seem to find how to stop the headers without using exit(); which then still means it won't show the echo, and any more use of ob_end_clean(); in any other ways causes the sent file to be empty. Only other thing I could think was having the echo in its own function, but as it runs at the same time the headers do it still places it in the file.
Many thanks for any help - Tom.
What you're dealing with is an HTTP request. The browser requests a URL with an HTTP request, the server sends a response. Click a link → browser sends request → server sends HTML page in response. Use Chrome, Safari or Firefox + Firebug and play around with the Network tab in their Web Inspector/development tools to get a real feeling for what's happening.
If you want to download a file, it works the same way. Only the server tells the browser through HTTP headers that this response is not an ordinary HTML page, but is supposed to be a file which it should save on disk.
As you should be able to see, there's no way to respond with a file download and an HTML page at the same time in one response. There's simply no way to do it. You have to output your HTML page with the message first, then link to the file download from there.

image button "save as" to save file from external servers php script

I have a pictrures gallery on my server. The pictures are stored on diffrent external servers. On my server are placed the thumbnails only.
How I can make a button "save as" in php so that a user can download a big picture file which is from external servers. I need a simple php script which can do download a jpg file cross all browser agents and from diffrent external servers. The button will be implemented inside html code. The button is a regular link formated in css style.
So how to do it properly. Thanks.
I would like also that the path of file should be send as a variable parameter to php script somehow.
I am guessing you are trying to have the pictures be downloaded automatically (you want a dialog box to pop up prompting where to save the file).
There is a great tutorial on this site that uses the php header function to force download
Check it out: http://www.ryboe.com/tutorials/php-headers-force-download
I found some solution with following php script
<?PHP
// Define the path to file
$file = $_GET['file'];
$name = basename ($file);
if(!file)
{
// File doesn't exist, output error
die('file not found');
}
else
{
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$name");
header("Content-Type: image/jpg");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file);
}
?>
and I can send parameters like url address cross html code
download
The only problem is that it is not working with all servers. It's not woriking for exemple with that file
http://backalleypics.com/Pictures/Letter Je~Ju/Jessica Alba/Jessica Alba 230.jpg
I don't know what I need to do?
Remove the spaces from your file name:
change: http://backalleypics.com/Pictures/Letter Je~Ju/Jessica Alba/Jessica Alba 230.jpg
to: http://backalleypics.com/Pictures/Letter_Je~Ju/Jessica_Alba/Jessica_Alba_230.jpg

Categories