PHP save browser output as file without saving file on server - php

I am trying to create link to save browser output as file without creating file on server.
This is what I got so far:
<?php
ob_start();
?>
<html>
webpage content
</html>
<?php
$page = ob_get_contents();
ob_end_flush();
$file= time().'.html';
file_put_contents($file, $page);
ob_start();
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
ob_end_flush();
?>
Download output as file
How can i create such link WITHOUT SAVING file on server?
Thank you for your suggestions/ideas/code.

Why that complicated? Do it straight forward instead:
<?php
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.time().'.html"');
?>
<html>
webpage content
</html>

You have two fairly easy options (there are others, but they would be more complicated) :
Option 1, use a data url:
$pageData = base64_encode($page);
$finfo = new finfo(FILEINFO_MIME);
$pageDataMime = $finfo->buffer($page);
$pageDataURL = 'data:' . $pageDataMime . ';base64,'.$pageData;
?>
Download output as file
Option 2, use query string to determine if output should be downloaded or not:
if($_GET['download_data']) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
echo $page;
exit();
} else {
// Output HTML as normal, including:
Download output as file
}

Open a file handle like this fopen('php://output', 'w'); and output to it.

Just echo $page:
<?php
ob_start();
?>
<html>
webpage content
</html>
<?php
$page = ob_get_contents();
ob_end_flush();
$file= time().'.html';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . strlen($page));
echo $page;
?>

Related

Displaying PDF to Browser with PHP not working

Using php's ability to call upon the browser to display a given PDF it doesn't work on my web host. But it works on my local xamp server with apache.
PHP:
$title = $_GET['title'];
$loc = $_GET['loc'];
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=".$title);
#readfile($loc);
Expected Output: Supposed to be the PDF document being rendered like it does on my local web server.
Actual but unwanted output:
%PDF-1.6 %���� 1638 0 obj <> endobj xref 1638 44 0000000016 00000 n ...
Can be seen here:
http://neilau.me/view.php?title=business-studies-hsc-notes-2006.pdf&loc=pdf/criteria/business-studies/2006/business-studies-hsc-notes-2006.pdf
Is this fixed through changing something on my cpanel? As my code isn't faulty... It works on my local web server.
Use this code
<?php
$file = 'dummy.pdf';
$filename = 'dummy.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
?>
You need to make sure you are not sending any text before writing headers.
Example of what not to do:
<!DOCTYPE html>
<html>
...
<?php
header("Content-type: application/pdf");
Example of how to fix that:
<?php
header("Content-type: application/pdf");
?>
<!DOCTYPE html>
<html>
...
In addition your script is very insecure. Here's what you should do, your entire PHP script should be:
<?php
$loc = filter_input(INPUT_GET,"loc");
$title = filter_input(INPUT_GET,'title')?:basename($loc);
if (!is_readable($loc)) {
http_response_code(404);
echo "Cannot find that file";
die();
}
if (strtolower(pathInfo($loc,PATHINFO_EXTENSION)) != "pdf") {
http_response_code(403);
echo "You are not allowed access to that file";
die();
}
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=".$title);
header("Content-Length: ".filesize($loc));
readfile($loc);
If you want to show things like a page title or a frame around it, you should use an iframe in another "wrapper" page:
<?php
$loc = filter_input(INPUT_GET,"loc");
$title = filter_input(INPUT_GET,'title')?:basename($loc);
?>
<html><head><title>My title</title></head>
<body>
<iframe src="/view.php?<?php echo ($loc?"loc=$loc":"").($title?"title=$title":"") ?>">
</iframe>
</body>
<html>

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

PHP echo before setting content type header?

I have the following PHP code:
function download_file($file, $description=null, $filename=false){
$filename = $filename || basename($file);
ob_start();
if(is_string($description)){
$description = preg_replace("/\$1/", $filename, $description);
echo $description;
}
sleep(2);
header('Content-Type: '.$this->file_mimetype($file));
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file) . "\"");
readfile($file);
header("Content-Type: text/html");
ob_end_flush();
}
download_file("https://raw.githubusercontent.com/Gethis/ED/master/easydevop.class.php", "Downloading easydevop.class.php");
The problem is that it is not echoing "Downloading easydevop.class.php" before the download. I also tried echoing it after all the headers, but that didn't work either. Please, any help?
As you can see I did use ob_start() and ob_end_flush()
You can't use "echo" (showing HTML-content) and send file to user at the same time.
You can show HTML-page first, and then redirect user to the file, using
HTML-redirect
<META HTTP-EQUIV="REFRESH" CONTENT="0;URL=http://url.to/file/or_script/that_send_file/">
or javascript redirect How do I redirect with Javascript?
As I already mentioned you cannot display echo when downloading file. When you download file you can just download file, nothing more.
However using JavaScript you can display message before starting downloading. Here is the test script:
<?php
if (isset($_GET['id'])) {
$file = 'testfile.txt';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script type="text/javascript">
function showDownload(message) {
document.getElementById("hidden").innerHTML = message;
document.getElementById("link1").style.display = 'none'; // you can even hide download link if you want
}
</script>
<div id="hidden"></div>
Download
</body>
</html>

PHP header to display a php file to another php file

Is it possible to display the content of a php file to another php file?
I have here an example where in the PDF is displayed in a php file.
<?php
$file = 'path of your PDF file';
$filename = 'custom pdf file name'; /* Note: Always use .pdf at the end. */
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
?>
but when I tried to display a php file to another php file. Its not working.
<?php
$file = 'path to my php file';
$filename = 'custom pphp file name';
header('Content-type: text/html');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
?>
Can anyone tell me what I'm doing wrong?
Here is one way to display the contents of another .php file:
show_included_file.php
<?php
include ('file1.php');
?>
file1.php
<?php
echo "This is the included file.";
?>
when upon entering show_included_file.php in your web browser,
will echo This is the included file if that is the intented result.
From a form input
Another way of showing content taken from a form (POST method) variable is this:
From a form input, for example <input type="text" name="variable_1">
Now if the user enters Hello world in the field,
then in your handler $variable_1 = $_POST['variable_1'];
you could then do echo $variable_1; and it would echo Hello world
PHP handler
<?php
$variable_1 = $_POST['variable_1'];`
echo $variable_1;
?>
I hope this is what you are looking for.
<?php
echo htmlentities(file_get_contents("yourphpfile.php"));

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