how to echo and filedownload together in php - php

The following code is mine.
I want to download a file and echo together in Php. But echo in end of code doesn't work, how to fixed this code?
$filename = trim($conf['savedir']).$_GET['task'].".".$_GET['hash'].".xml";
$downname = $_GET['task'].'.'.$_GET['hash'].'.xml';
$fp = fopen($filename, 'r');
if($fp == null)
{
echo "Wrong Access1";
} else {
header('Content-type:text/xml charset=utf-8');
header('Content-disposition: attachment; filename='.$downname);
header('Content-length:'.filesize($filename));
header('Content-transfer-encoding: binary');
header('Pragma: no-cache');
header('Expires: 0');
fpassthru($filename);
fclose($fp);
echo $_GET['task'].'.'.$_GET['hash'].'.xml file download.';
}

Like #Mark Backer said, you can't echo and download at the same time for the same request, but there are some "tricks" to echo something and download the file.
Let's suppose that your code from the question is located into test.php file and the user requests the file that contains the code bellow:
<script type="text/javascript">
window.open('test.php?task=<?=$_GET['task']?>&hash=<?=$_GET['hash']?>', '_blank');
</script>
<?php
echo $_GET['task'].'.'.$_GET['hash'].'.xml file download.';
So, the javascript code will pass the $_GET variables to test.php open a new window for download and in echo your message in the current window.

Related

how to download file in php

I want to download image file in php.
<?php
if(isset($_REQUEST["file"])){
$filepath = BASE_URL.'assets/uploads/save_template_images/template1_221594899972.png';
// Process download
if(file_exists($filepath)) {
echo $filepath;
exit;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
flush(); // Flush system output buffer
readfile($filepath);
die();
} else {
echo $filepath;
exit;
http_response_code(404);
die();
}
}
?>
In my index page, I have an anchor tag and if click on anchor tag then above code run. I am not showing anchor tag because, I put the $filepath static value in above code. When I run above code then it goes on else condition. I think, full path of project is not taking by above code. If I put image in same folder then it downloads.
First ensure allow_url_fopen setting in php.ini file is turned on. After that Use this code to download your file:
<?php
$url = 'https://lokeshdhakar.com/projects/lightbox2/images/image-5.jpg';
$file = './files/'.basename($url);
file_put_contents($file, file_get_contents($url));
?>
For successful download, files directory must be exists. But I think it would be inefficient to add directory existence check as I think you already know where to save the file you are downloading.

PHP force download corrupt PDF file

I have gone through all articles on Stack Overflow and can't fix my issue. I am using following code:
$file = $_GET['url'];
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
The above mention code is downloading the file from the directly above the root and Yes it is downloading a PDF file but the file is only of 1KB size and not the original size. The $_GET['url'] is receiving ../dir/dir/filename.pdf in it. the filename is space in it as well. For security reason I cannot share the file name.
Please let me know where am I going wrong.
Please make sure you are using the web server path to access the file - for instance your path could be: /home/yourusername/public/sitename/downloads/<filename>, you should check first - to help you can run this at the top of your PHP script to find out the full path for the current script:
echo '<pre>FILE PATH: '.print_r(__FILE__, true).'</pre>';
die();
Only send the filename with the url using urlencode() and on the receiving PHP script use urldecode() to handle any character encoding issues.
See here: http://php.net/manual/en/function.urlencode.php
and here: http://php.net/manual/en/function.urldecode.php
So where you create your url:
Download File
And in your php script:
$file_base_path = '/home/yourusername/public/sitename/downloads/';
$file = urldecode($_GET['url']);
$file = $file_base_path . $file;
$file = $_GET['url'];
if (file_exists($file))
{
if (FALSE!== ($handler = fopen($file, 'r')))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: chunked'); //changed to chunked
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
//header('Content-Length: ' . filesize($file)); //Remove
//Send the content in chunks
while(false !== ($chunk = fread($handler,4096)))
{
echo $chunk;
}
}
exit;
}
echo "<h1>Content error</h1><p>The file does not exist!</p>";
I hope this helps you!

How to download a text file on link click in codeigniter

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));
}

header () in php not downloading the file

I am trying to read the file from php and downloading it from the ui on click of a button
<?php
$file = 'download.csv'; //path to the file on disk
if (file_exists($file)) {
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=contact-list.csv');
header('Pragma: no-cache');
readfile($file);
//unlink($file);
exit;
}
else {
print "file not found!!!";
}
?>
But the file is not getting downloaded. No error, the code is working. unlink() function deleted the file.
Assuming my comment answers yes to all, then the only think i see that might be an issue.
application/csv
Should be:
text/csv

Let the client to download a file from the server

I need to implement a code where I can let the client to download one or more local files on the web server.
I have 3 files: file1.php, file2.js, file3.php with the following codes.
In file1.php:
<select name="file_list" class="myclass" id="f_list" style="height:25px; width: 280px">
<?php
foreach (new DirectoryIterator("$filesFolder") as $file)
{
if((htmlentities($file) !== ".") && (htmlentities($file) !== ".."))
{
echo "<option>" . htmlentities($file) . "</option>";
}
}
?>
</select>
<?php
echo "<input type=\"button\" value=\" Download \" onClick=\"downloadFile()\"/>";
?>
in file2.js
function downloadFile()
{
$("#activity").html("<img src=\"img.gif\" style=\"left: 590px;top: 74px;margin: auto;position: absolute;width: 32px;height: 32px;\" />");
$("#content").load("file3.php",
{
filename: $("#f_list").val()
});
}
file3.php
if(isset($_POST["filename"]))
{
$filename = $_POST["filename"];
/* testing string */
echo $filesFolder.$filename;
if(file_exists($filesFolder.$filename))
{
ob_start();
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filesFolder.$filename));
readfile($filesFolder.$filename);
ob_end_flush();
exit;
}
}
I took this last PHP code from the readfile function PHP manual because the behaviour is exactly what I need. But when file3.php is executed, the content of the file (which is binary data) is printed out on the screen.
I think I am missing to implement some feature but I don't know what it could be.
How can I obtain the same result of the readfile PHP manual page?
Thank you in advance for your help.
File2:
You can't use .load() or similar methods to download a file.
Just use window.location.href = "file3.php?filename="+$("#f_list").val();
File3:
You can't output anything before calling header()s. Comment out echo on line 5.
In File 2 we are using GET instead of POST, replace $_POST with $_GET.
It might also help to not request the page using ajax, just use
window.location.href='/download/url';
If all headers are correct, it will open a download dialog without leaving the current page.
One way would be to try to open the file in a new tab/window:
function downloadFile()
{
window.open("file3.php?filename=" + encodeURIComponent($("#f_list").val()));
}
Because the result of the PHP page has headers indicating that the content is a download not a page, the browser will not actually navigate, but will instead offer a download box. Note that this method uses GET not POST, so you will have to change from $_POST to $_GET or $_REQUEST in file3.php. Also, make sure you remove your echo before the headers go out or this won't work.

Categories