How to download a text file on link click in codeigniter - php

I have text file contains Sample of CSV file format, I want my users can download that file on a link click.
This file resides in this folder stucture:
assets->csv->Sample-CSV-Format.txt
This is the code that I have tried to far:
<?php
$file_name = "Sample-CSV-Format.txt";
// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.') + 1);
header('Content-disposition: attachment; filename=' . $file_name);
if (strtolower($ext) == "txt") {
// works for txt only
header('Content-type: text/plain');
} else {
// works for all
header('Content-type: application/' . $ext);extensions except txt
}
readfile($decrypted_file_path);
?>
<p class="text-center">Download the Sample file HERE It has a sample of one entry</p>
This code is downloading the file on page load instead of link click. Also, it is downloading the whole html structure of the page I want only the text what I have written in text file.
Please guide where is the issue?

You can do this simply in by HTML5 download atrribute . Just add this line in your downloading link .
HERE

You can do it like this, it won't redirect you and also works good for larger files.
In your controller "Controller.php"
function downloadFile(){
$yourFile = "Sample-CSV-Format.txt";
$file = #fopen($yourFile, "rb");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=TheNameYouWant.txt');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($yourFile));
while (!feof($file)) {
print(#fread($file, 1024 * 8));
ob_flush();
flush();
}
}
In your view "view.php"
Download

make it like this
someother_file.php
<?php
$file_name = "Sample-CSV-Format.txt";
// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);
header('Content-disposition: attachment; filename='.$file_name);
if(strtolower($ext) == "txt")
{
header('Content-type: text/plain'); // works for txt only
}
else
{
header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);
?>
some_html_page.html
<p class="text-center">Download the Sample file HERE It has a sample of one entry</p>

To my view its better to have the download code to the client side, than to have a controller-method written for this.
you can use this ref

public function getTxt()
{
$this->load->helper('download');
$dataFile = "NOTE87";
$dataContent = array();
$dt = "Date :23/07/2021";
$dataContent= array(
"\n",
"\t\t\tUTI AMC Limited\n",
"\t\tDepartment of Fund Accounts\n",
"\n",
"\tReissue of Non Sale Remittance - Axis Bank Cases\n",
"\n",
"\t\t\t\tDate :".$dt."\n",
"\n",
);
force_download($dataFile,implode($dataContent));
}

Related

create file from php unpacking file_get_contents

<?php
// // $bin = pack("S", 65535);
// // $ray = unpack("S", $bin);
// $ray = pack("H*hex", $data);
// print_r($ray);die();
// echo "UNSIGNED SHORT VAL = ", $ray[1], "\n";
$file = file_get_contents("C:\\Users\\qwerty\Downloads\\image001.jpg", true);
// $file = file_get_contents("C:\\Users\\qwerty\\Downloads\\request.pdf", true);
$data = '0x'.unpack('H*hex', $file)['hex'];
header('Content-Description: File Transfer');
header("Content-Transfer-Encoding: Binary");
// header('Content-Disposition: attachment; filename="request.pdf');
header('Content-Disposition: attachment; filename="image001.jpg');
header('Cache-Control: must-revalidate');
header('Content-Length: 80685');
echo $data;
?>
I want am trying to create File from unpacking the same file. I am recreating this from my other function that unpacks a file stores the data in database and recreate the file again using the data. The above is my sample demo for the bigger function. What it does is unpack file content then echo again. Problem is the downloaded file (image or pdf) cant be opened. Any idea is appreciated
I think I saw the problem when I opened the file in notepad it has a newline before the image data how can I make sure there will be no new line in before the data?

php download link to rar

I'm creating a website on my localhost that should let people download some .rar files.
In my index I've created some tags like this:
$filename = "Test001.rar";
'.$filename.'';
This is just an example of one single file, but in my php file 'download.php' I've got the problem when I want to download the .rar file
This is download.php
<?php
echo "Welcome to Knowledge!";
if (isset($_GET['file']) && basename($_GET['file']) == $_GET['file'])
{
$file = $_GET["file"];
$path = 'C:\xampp\htdocs\TestSite'."\\".$file;
}
$err = $path.'Sorry, the file you are requesting doesnt exist.';
if (file_exists($path) && is_readable($path))
{
//get the file size and send the http headers
$size = filesize($path);
header('Content-Type: application/x-rar-compressed, application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$file);
header('Content-Transfer-Encoding: binary');
readfile($filename);
}
?>
It opens the stream in the right way, but I get that the file size is about 200 bytes and not the full length that is about 200MB.
How can I fix this problem?
Remove the echo statement, there should not be any output before the headers. Change readfile($filename) to readfile($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);

PHP Header download PDF

I've made a page where you can go and write text in a "textarea" and then when you click download you download that file as a .txt file. I've done the same thing to some other extensions and that is working fine. But it won't work with .PDF, nothing I read works. Here is the snippet I use for the .PDF downloading:
<?php
if($fileFormat == ".pdf"){
$content = $_POST['text'];
$name = stripslashes($_POST['name']);
$nameAndExt = $name.".pdf";
print strip_tags($content);
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="'.$nameAndExt.'"');
header('Content-Transfer-Encoding: binary ');
}
?>
I'm grateful for any answear, thanks!
// hold the filename for use elsewhere so you don't have to append .pdf every time
$filename = "$id.pdf";
// create the file
$pdf->output( $filename );
// set up the headers
header("Content-Description: File Transfer");
header("Content-disposition: attachment; filename={$filename}");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($file));
// push the buffer to the client and exit
ob_clean();
flush();
// read the file and push to the output stream
readfile( $filename );
// remove the file from the filesystem
unlink( $filename );
exit();
I would recommend a class like TCPDF, see http://www.tcpdf.org/. I used it couple of times and it's quite nice (open source).

Cannot download pdf using ipad

I am using the following function to download pdf file it is working fine when i download it from PC or laptop but when i click on download link using ipad it opens a page with lots of special chracters and I am unable to download the file.
My download function is
public function download() {
$download_path = $_SERVER['DOCUMENT_ROOT'] . "/import";
$filename = $_GET['file'];
$file = str_replace("..", "", $filename);
$file = "$download_path/$file";
if (!file_exists($file))
die("Sorry, the file doesn't seem to exist.");
$type = filetype($file);
header("Content-type: $type");
header("Content-Disposition: attachment;filename=$filename");
header('Pragma: no-cache');
header('Expires: 0');
readfile($file);
}
Any idea about this error ?
This is probably the issue:
$type = filetype($file);
header("Content-type: $type");
From the manual
Possible values are fifo, char, dir, block, link, file, socket and
unknown.
Which are not things you want to see in the header. You are probably looking for:
header('Content-type: application/pdf');
You probably want finfo_file() and not filetype().

Categories