How to download file from database/folder using php - php

File uploaded will be store in database and folder (folder name: uploads).Now I want to know how to create download file from database/folder. I have two file butangDonload.php and download.php. When user click word "donload" the pop up box will appear and save the file.
butangDonload.php
<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."'>donload</a> ";
?>
download.php
<?php
$name= $_GET['nama'];
download($name);
function download($name) {
$file = $nama_fail;
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));
ob_clean();
flush();
readfile($file);
exit;
}
}
?>

I have changed to your code with little modification will works well.
Here is the code:
butangDonload.php
<?php
$file = "logo_ldg.png"; //Let say If I put the file name Bang.png
echo "<a href='download1.php?nama=".$file."'>download</a> ";
?>
download.php
<?php
$name= $_GET['nama'];
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=\"" . basename($name) . "\";");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($name));
ob_clean();
flush();
readfile("your_file_path/".$name); //showing the path to the server where the file is to be download
exit;
?>
Here you need to show the path from where the file to be download.
i.e. will just give the file name but need to give the file path for reading that file. So, it should be replaced by
I have tested by using your code and modifying also will works.

here is the code to download file with how much % it is downloaded
<?php
$ch = curl_init();
$downloadFile = fopen( 'file name here', 'w' );
curl_setopt($ch, CURLOPT_URL, "file link here");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 65536);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'downloadProgress');
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt( $ch, CURLOPT_FILE, $downloadFile );
curl_exec($ch);
curl_close($ch);
function downloadProgress ($resource, $download_size, $downloaded_size, $upload_size, $uploaded_size) {
if($download_size!=0){
$percen= (($downloaded_size/$download_size)*100);
echo $percen."<br>";
}
}
?>

You can use html5 tag to download the image directly
<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."' download>donload</a> ";
?>
For more information, check this link
http://www.w3schools.com/tags/att_a_download.asp

butangDonload.php
$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;
Try this,
<?php
$name=$_SESSION['name'];
download($name);
function download($name){
$file = $nama_fail;
?>

You can also use the following code:
<?php
$filename = $_GET["nama"];
$contenttype = "application/force-download";
header("Content-Type: " . $contenttype);
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");
readfile("your file uploaded path".$filename);
exit();
?>

function downloadFiles($dir, $file) {
header("Content-type: application/force-download");
header('Content-Disposition: inline; filename="' . $dir . $file . '"');
header("Content-Transfer-Encoding: Binary");
header("Content-length: " . filesize($dir . $file));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file . '"');
readfile("$dir$file");
}
$dir = "folder_path";
$file = "image_name.jpg";
$download = downloadFiles($dir,$file);
Try this way, it is helpful for me.

Related

File downloaded with headers doesn't work

I'm trying to download an audio ogg file with a dynamic url
function getAudio($fileName){
$localFile = __DIR__ . '/../../../shared/call_review/' . $fileName;
$fp = fopen($localFile, 'r');
$fp or die('Could not open file "' . $fileName . '"' . PHP_EOL);
$contents = fread($fp, filesize($localFile));
$contents or die('could not read file');
header('Content-Description: File Transfer');
header('Cache-Control: public');
header('Content-Type: audio/ogg');
header("Content-Transfer-Encoding: binary");
header('Content-Length: '.filesize($contents));
header("Content-Type: audio/ogg");
header("Content-Disposition: attachment; filename=" . $fileName);
echo $contents;
exit();
}
But after file is saved, it doesn't work, or is corrupt.
The problem seems to be this line:
header('Content-Length: '.filesize($contents));
The file size should come from filesize($localFile) as demonstrated several lines earlier,
so it should be:
header('Content-Length: '.filesize($localFile));
Or just use the length of the $contents variable:
header('Content-Length: '.strlen($contents));

php download script not working

The below .php script doesn't work for me - it just prints jibberish:
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/rapcDemo/documents/";
$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);
?>
Any ideas what I am doing wrong?
Well... This is the script I use. Maybe it will help.
Main donwload script:
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/rapcDemo/documents/";
$fullPath = $path.$_GET['download_file'];
if(is_file($fullPath)) {
# required for IE
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
# get the file mime type using custom function
$mime = ($try = get_mime($fullPath)) ? $try : "application/octet-stream";
# set headers for download
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($fullPath)) . ' GMT');
header('Cache-Control: private', false);
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . $_GET['download_file']. '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($fullPath)); // provide file size
header('Connection: close');
readfile($fullPath); // push it out
exit();
}
?>
And this is my get_mime() function:
<?php
function get_mime($url = "") {
if (empty($url))
return FALSE;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$results = explode("\n", trim(curl_exec($ch)));
foreach ($results as $line)
if (strtok($line, ':') == 'Content-Type')
return trim(explode(":", $line)[1]);
return FALSE;
}
?>
Ok! I just found and modified a php script online that works like a charm:)
The link is below:
http://phpsnips.com/579/PHP-download-script-for-Large-File-Downloads

Download file php in the server

in the localhost i get everything perfect but when i upload it to the server i get this error
Warning: Cannot modify header information - headers already sent by(
hier is my code
<?php
function download($file){
$dir = './download/';
$path = $dir.$file;
if(!file_exists($path)){
die('Error');
}else{
header('Content-Description : File Transfer');
header('Content-Disposition : attachment; filename='.basename($path));
header('Content-Type: application/octet-stream');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
ob_start();
flush();
readfile($path);
exit;
}
}
if (isset($_GET['download'])) {
if (!empty($_GET['download'])) {
$file = $_GET['download'];
download($file);
}
}
?>
<a class="download-template" href="example.php?download=Modern.rar">Download</a>
Remove the whitespace before the <?php
Like so
<?php
function download($file){
$dir = './download/';
$path = $dir.$file;
if(!file_exists($path)){
die('Error');
}else{
header('Content-Description : File Transfer');
header('Content-Disposition : attachment; filename='.basename($path));
header('Content-Type: application/octet-stream');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
ob_start();
flush();
readfile($path);
exit;
}
}
if (isset($_GET['download'])) {
if (!empty($_GET['download'])) {
$file = $_GET['download'];
download($file);
}
}
?>
<a class="download-template" href="example.php?download=Modern.rar">Download</a>
The error is telling you that you're outputting content before it should do.
If you output content then the page headers have already been sent, so your call to header() will fail because the headers have already gone. And headers are always sent first.
By removing the whitespace there is no content to send, so the headers are not sent, so the call to header will then work and not error.
Change the file encoding to "without BOM" (e.g. using notepad++) or remove the BOM before
Use the following code for download any type of file extensions(including .php,.html):
<?php
$filename = $test_data['test_name'];
$contenttype = "application/octet-stream";
header("Content-Type: " . $contenttype);
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");
readfile(ADMIN_ROOT.'modules/tests/test_pdfs/'.$filename);
exit();
?>
Or you can check in this link working example:
http://websamplenow.com/29/file_download

View PDF in browser rather than download

There are meetings on this website and each meeting has a PDF attached showing the meeting minutes. The next meeting that takes place dynamically collects this attached PDF and allows for a download as the previous minutes. This is all working perfectly, however, when clicking the link for the previous minutes it always opens up a save as box. I was wondering how to get this to just display in the browser (assuming the user has a PDF viewer enabled)?
Here is the function from the controller:
public function current_pdf($id = null, $pdf = null) {
$this->loadModel('Document');
$document = $this->Document->find('list', array(
'fields' => array('Document.dir', 'Document.url')
));
$request_pdf = $this->Meeting->read(null, $id);
if ($pdf == 'current') {
$file = $document[$request_pdf['Meeting']['minutes']];
if (!empty($file)) {
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize(WWW_ROOT . 'files/document/url/' . $request_pdf['Meeting']['minutes'] . '/' . $file));
flush(); // this doesn't really matter.
$fp = fopen(WWW_ROOT . 'files/document/url/' . $request_pdf['Meeting']['minutes'] . '/' . $file, "r");
while (!feof($fp)) {
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
//echo WWW_ROOT.'files/document/url/pdf/'.$file; die;
//readfile(WWW_ROOT.'files/document/url/pdf/'.$file);
exit;
}
$this->redirect(array('controller' => 'meetings', 'action' => 'view/' . $id));
} else {
$file = $request_pdf['Meeting']['current_minutes'];
if (!empty($file)) {
//echo filesize(WWW_ROOT.'files/document/url/pdf/'.$file); die;
/* header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' . urlencode(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(); */
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize(WWW_ROOT . 'files/document/url/pdf/' . $file));
flush(); // this doesn't really matter.
$fp = fopen(WWW_ROOT . 'files/document/url/pdf/' . $file, "r");
while (!feof($fp)) {
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
//echo WWW_ROOT.'files/document/url/pdf/'.$file; die;
//readfile(WWW_ROOT.'files/document/url/pdf/'.$file);
exit;
}
$this->redirect(array('controller' => 'meetings', 'action' => 'view/' . $id));
}
}
And here is the link in the view:
<?php echo $this->Html->link(__('Download Previous Minutes'), array('controller' => 'meetings', 'action' => 'current_pdf', $download, 'current')); ?>
I have tried removing the header("Content-Type...") lines of code and changing attachment in header("Content-Disposition: attachment; filename=" . urlencode($file)); to inline. This stopped the save as pop-up but displayed a load of spurious code in the browser instead.
Any help would be greatly appreciated as I'm currently very confused.
I believe this is as simple as removing this line in your code:
header("Content-Disposition: attachment; filename=" . urlencode($file));
This line will server up the file as a download, and not display the content in the browser.
I hope that helps!

PHP file Download without saving to my directory?

I have to create one text file and make it downloadable without saving to my directory on button click.
Below I have mentioned code of my file that generate file.
<?php
$data = "ffff dfjdhjf jhfjhf f f hlm hoejrherueirybgb,nvbd;ihrtmrn.";
$filename = "SU_Project_Startup.txt";
$fh = fopen($filename, "w+");
fwrite($fh, $data, strlen($data));
fclose($fh);
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
ob_end_flush();
echo $data;
exit();
?>
Can you tell me which changes still I have to do in this code?
Thanks in advance
Try this headers:
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/json"); // here is your type
header("Content-Transfer-Encoding: binary");
This is an example of taking pictures of the url
you can try it, or put it into function
<?php
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="File-name.jpg"');
$fileurl = 'http://upload.wikimedia.org/wikipedia/commons/thumb/c/cc/Ramses_II_at_Kadesh.jpg/120px-Ramses_II_at_Kadesh.jpg';
$data = file_get_contents($fileurl);
echo $data;
?>

Categories