Download html textarea content as a file - php

I am working on a project where the requirement is to download a textarea content as a .txt file on a wordpress site.
After searching previous questions, I got below code which marked as a correct answer.
<html>
<body>
<form action="#" method="post">
<textarea name="text" rows="20" cols="100"></textarea>
<input type="submit" value="submit">Download Text</input>
</form>
<?PHP
if(isset($_POST['submit']))
{
$text = $_POST['text'];
print ($text);
$filename = 'test.txt';
$string = $text;
$fp = fopen($filename, "w");
fwrite($fp, $string);
fclose($fp);
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: application/txt');
readfile('test.txt');
}
?>
</body>
</html>
But for me it is not creating a .txt file. please help me to identify the issue

Modified little bit in your code.
First put your php code
<?php
if(isset($_POST['submit']))
{
$text = $_POST['text'];
print ($text);
$filename = 'test.txt';
$string = $text;
$fp = fopen($filename, "w");
fwrite($fp, $string);
fclose($fp);
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: application/txt');
readfile('test.txt');
die; //modified code
}
?>
after that put your html code
<html>
<body>
<form action="#" method="post">
<textarea name="text" rows="20" cols="100"></textarea>
<input type="submit" value="submit" name="submit">Download Text</input>
</form>
add name attribute in submit button.

Your code actually creates a file on the server and it does not get deleted afterwards. If the code failed, it is possible that you didn't have permission to write on your server. You can trim your code down to the following so as no file is generated in the process:
<?php
if(isset($_POST['text']))
{
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: application/txt');
echo $_POST['text'];
exit; //stop writing
}
?>
<html>
<body>
<form action="" method="post">
<textarea name="text" rows="20" cols="100"></textarea>
<input type="submit" value="submit" name="submit">Download Text</input>
</form>
</body>
</html>
Firstly, you should output the file before printing anything on screen and secondly, you forgot to add name="submit" to your original code. I didn't use it here, but I included for you to get an idea.
In the WordPress Context:
Add this to your functions.php or plugin file:
function feed_text_download(){
if(isset($_POST['text_to_download']))
{
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: application/txt');
echo $_POST['text_to_download'];
exit; //stop writing
}
}
add_action('after_setup_theme', 'feed_text_download');
Add the form to one of your template files or in the HTML editor of your post:
<form action="" method="post">
<textarea name="text_to_download" rows="20" cols="100"></textarea>
<input type="submit" value="submit" name="submit">Download Text</input>
</form>
It should be good :)
EDIT: Add Filename
HTML:
<form action="" method="post">
<label>Filename:<input type="text" name="filename" /></label>
<label>Text:<textarea cols="100" name="text_to_download" rows="20"></textarea></label>
<input type="submit" name="submit" value="Download Text" />
</form>
PHP:
function feed_text_download() {
if ( isset( $_POST['text_to_download'] ) && isset( $_POST['filename'] ) ) {
$filename = sanitize_file_name( $_POST['filename'] );
header( 'Content-disposition: attachment; filename=' . $filename );
header( 'Content-type: application/txt' );
echo $_POST['text_to_download'];
exit; //stop writing
}
}
add_action( 'after_setup_theme', 'feed_text_download' );

Try following code, that will help you:
<?php ob_start();?>
<html>
<body>
<?php
if(isset($_POST['tarea'])){
$filename = 'test.txt';
$data = $_POST['tarea'];
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
echo $data;
exit;
}
?>
<form action="" method="post">
<textarea name="tarea"></textarea>
<input type="submit">
</form>
</body>
</html>

Related

PHP including HTML in readfile

I have the following code which kind of works but for some reason the $download includes the part inside into the downloaded file.
<form method="post">
<button id="click" name="click">Download</button>
</form>
<?php
if(isset($_POST['click'])){
$files = scandir('/local/path', SCANDIR_SORT_DESCENDING);
$newest_file = $files[0];
$download = $newest_file;
header("Content-Type: text/plain");
header('Content-Disposition: attachment; filename="'.$download.'"');
readfile("/local/path/$download");
}
?>
Downloaded file
form method="post">
<button id="click" name="click">Download</button>
</form>
Start-of-the-actual-log
blabla
blabla
blabla
What is causing this to happen? I only want to download the newest file in a folder.
Dont print anything or send header before downloading, look at this :
<?php
if(isset($_POST['click'])){
$files = scandir('/local/path', SCANDIR_SORT_DESCENDING);
$newest_file = $files[0];
$download = $newest_file;
header("Content-Type: text/plain");
header('Content-Disposition: attachment; filename="'.$download.'"');
readfile("/local/path/$download");
}else{
echo'
<form method="post">
<button id="click" name="click">Download</button>
</form>';
}
?>

PHP Download Button Not Working Generate Empty File

I have two button in the form, one is to submit and second button download the output shown in the textarea.
The submit works fine but download button create empty file and does not write data of output text area.
Here is code:
<?php
error_reporting(0);
$mytext = "";
$txt = preg_replace('/\n+/', "\n", trim($_POST['inputtext']));
$text = explode("\n", $txt);
$output = array();
if(isset($_POST["submit"]))
{
for($i=0;$i<count($text);$i++)
{
$output[] .= trim($text[$i]) . ' Text added with output'.PHP_EOL;
}
}
if(isset($_POST["download"]) ) {
$handle = fopen("file.txt", "w");
fwrite($handle, implode($output));
fclose($handle);
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment;filename='.basename('file.txt'));
header('Expires: 0');
ob_end_clean();
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
}
?>
<form method="POST" action="test.php">
<textarea name="inputtext" rows="10" cols="100" placeholder="Enter Any Text!" required><?php if(!empty($_POST["inputtext"])) { echo $_POST["inputtext"]; } ?></textarea>
<br><br>
<input type="submit" name="submit" value="Do it!">
<br><br>
<p>Output goes here. </p><textarea name="oputputtext" rows="10" cols="100" ><?php echo implode($output);?></textarea>
<input type="submit" name="download" value="Download Output">
</form>
You have to generate the output also if downloading (unless you take it from the second textarea), so use if(isset($_POST["submit"]) || isset($_POST["download"]) ) in the test, instead of only if(isset($_POST["submit"]))
The final code would look like this:
<?php
error_reporting(0);
$mytext = "";
$txt = preg_replace('/\n+/', "\n", trim($_POST['inputtext']));
$text = explode("\n", $txt);
$output = array();
/* CHANGED HERE */
if(isset($_POST["submit"]) || isset($_POST["download"]) ) {
for($i=0;$i<count($text);$i++) {
$output[] .= trim($text[$i]) . ' Text added with output'.PHP_EOL;
}
}
if(isset($_POST["download"]) ) {
$handle = fopen("file.txt", "w");
fwrite($handle, implode("\r",$output));
fclose($handle);
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
ob_end_clean();
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
}
?>
<form method="POST" action="test.php">
<textarea name="inputtext" rows="10" cols="100" placeholder="Enter Any Text!" required><?php if(!empty($_POST["inputtext"])) { echo $_POST["inputtext"]; } ?></textarea>
<br><br>
<input type="submit" name="submit" value="Do it!">
<br><br>
<p>Output goes here. </p>
<textarea name="oputputtext" rows="10" cols="100" ><?php echo implode($output);?></textarea>
<input type="submit" name="download" value="Download Output">
</form>

Export MySQL table to CSV with custom header

Why when i try to export MySql table to CSV with header('Content-Disposition:attachment; filename="'.$filename.'"'); It doesn't get done properly:
it does create the CSV file
however it does it on the beginning of the file, where the page code is
and after the code the is table content
This is the code witch exports it:
$this->view->table = $model->info('name');
$is_csv = $this->_getParam('csv');
if ($this->_request->isPost() && $is_csv) {
$fichier = 'file.csv';
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="'.$fichier.'"');
$fp = fopen('php://output', 'w+');
$data = $model->fetchAll();
foreach ($data as $fields) {
fputcsv($fp, $fields->toArray());
}
fclose($fp);
}
And here i'm calling this with button:
<form method="post">
<input type="hidden" name="table" value="<?php echo $this->table ?>" />
<button type="submit" class="btn" name="csv" value="csv">
<?php echo Core_Locale::translate('CSV')?>
</button>
</form>
put this code up in your application then application create view.
I had same issue but i solved it this way..
i put peace of code to function/block and place it over echo or render html
put exit; on the end of function/block
if(isset($_POST['submit'])) {
$csv = new Csv();
$filename = $csv->generateFileDate();
if($filename !== false) {
$data = file_get_contents($csv->folder .'reports/'. $filename);
header('Content-Type: application/csv; charset=utf-8');
header('Content-Disposition: attachement;filename="'.$filename.'";');
echo $data;
exit;
}
}
?>
<!doctype html>
<html lang="us">
<head> .........
hope this help to you

Exporting multiple CSV files from MySQL into zip

Major Edit: I've updated my code to better include the Archive class, as well as the ZIP download. The table is written to the database just fine, but I get an error in my error log saying "No such file or directory." Where do I write the file per table?
Thanks so much for any help/suggestions!
Below is my code:
HTML Form
if($_POST['submit']){
if(empty($_POST['jobtitles'])) echo "<strong>Error: You have not entered a Job Title, please go back and enter one.</strong>";
else echo "<strong>Your documents are processing and being exported.</strong>";
}
?>
<body>
<center><strong><u>BLS Data Processor and Exporter</u></strong></center>
<form method="post" action="handler.php">
<p>Enter all of the desired jobs, each separated by a new line. Note: All jobs must be spelled exactly as contained in the BLS data</p>
<textarea name="jobtitles" rows="10" cols="50">
</textarea>
<p>Upon clicking submit, your tables will be generated and exported as a CSV file</p>
<p>Select the table types you would like to receive</p>
<input type="checkbox" name="tabletype[]" value="local">Local<br>
<input type="checkbox" name="tabletype[]" value="msa">MSA<br>
<input type="checkbox" name="tabletype[]" value="nmsa">NMSA<br>
<input type="checkbox" name="tabletype[]" value="state">State<br>
<input type="checkbox" name="tabletype[]" value="nat">National<br>
<input type="submit" value="Submit and Export">
</form>
</body>
PHP side
header("Content-disposition: attachment; filename=".$fileName);
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: application/zip;\n");
header("Pragma: no-cache");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public");
header("Expires: 0");
// Create the ZIP file
$zip = new ZipArchive;
$result_zip = $zip->open($fileName, ZipArchive::CREATE); // We open the file
if ($result_zip === TRUE) {
$pdo = new PDO("mysql:host=localhost;dbname=BLSdata","root","root");
$tableList = $pdo->prepare('SHOW TABLES FROM BLSdata LIKE "localTable" AND "msaTable" AND "nmsaTable" AND "stateTable" AND "natTable"');
$tableList->execute(array(''));
// For each table
foreach($tableList as $aTableList)
{
$content = export_table($aTableList[0]);
$fileName = $aTableList[0].'.csv';
$zip->addFile($fileName, $fileName);
}
$zip->close();
}
else
{
echo 'Failed, code:' . $result_zip;
}
readfile($fileName);
$deleteLocal = "DROP TABLE localTable";
$pdo->query($deleteLocal);
exit();

Downloading MP3 and MP4 files using PHP

I am making a downloader for mp3 and mp4 and i want two php files in php with 2 buttons calling both php files but only the first php file works.
code for popup.php
<?php
include "downloadmp3.php";
include "downloadmp4.php";
?>
<html>
<head></head>
<body bgcolor="#E6E6E6">
<form method="post">
<label for="url">Download mp3:</label>
<input type="text" name="url" value="" id="url">
<input type="submit" name="submit" value="Download">
<hr>
</form>
<form method="post">
<label for="url1">Download mp4:</label>
<input type="text" name="url1" value="" id="url1">
<input type="submit" name="submit" value="Download">
</form>
</body>
</html>
code for downloadmp3.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$url = (isset($_POST['url']) && !empty($_POST['url'])) ? $_POST['url'] : false;
if (!$url) {
echo "Vul alstublieft een url in";
} else {
$source = file_get_contents($url);
$source = urldecode($source);
// Verkrijg de video titel.
$vTitle_results_1 = explode('<title>', $source);
$vTitle_results_2 = explode('</title>', $vTitle_results_1[1]);
$title = trim(str_replace(' – YouTube', ”, trim($vTitle_results_2[0])));
// Extract video download URL.
$dURL_results_1 = explode('url_encoded_fmt_stream_map', "url=", $source);
$dURL_results_2 = explode('\u0026quality', $dURL_results_1[1]);
// Force download van d video.
$file = str_replace(' ', '_', strtolower($title)).'.mp4';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: video/mp4");
header("Content-Transfer-Encoding: binary");
readfile($dURL_results_2[0]);
exit;
}
}
?>
and code for downloadmp4.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$url = (isset($_POST['url1']) && !empty($_POST['url1'])) ? $_POST['url1'] : false;
if (!$url) {
echo "Vul alstublieft een url in";
} else {
$source = file_get_contents($url);
$source = urldecode($source);
// Verkrijg de video titel.
$vTitle_results_1 = explode('<title>', $source);
$vTitle_results_2 = explode('</title>', $vTitle_results_1[1]);
$title = trim(str_replace(' – YouTube', ”, trim($vTitle_results_2[0])));
// Extract video download URL.
$dURL_results_1 = explode('url_encoded_fmt_stream_map', "url1=", $source);
$dURL_results_2 = explode('\u0026quality', $dURL_results_1[1]);
// Force download van d video.
$file = str_replace(' ', '_', strtolower($title)).'.mp4';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: video/mp4");
header("Content-Transfer-Encoding: binary");
readfile($dURL_results_2[0]);
exit;
}
}
?>
Updated:
Form submitted for MP3 form works.
But form submitted for MP4 doesn't works.
Please provide an solution to make it work.
Only first php file calls are working because of the following if condition:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
Since downloadmp3.php has been included first therefore it's if condition is giving the result.
Use proper form handler to make it work.
Also the best practice is to use unique names for the forms.
This code is working fine for me in all the browsers and the downloaded file is playing good :
download-audio.php
<?php
$file = $_GET['file'];
header ('Content-type: octet/stream');
header ('Content-disposition: attachment; filename='.$file.';');
header('Content-Length: '.filesize($file));
readfile($file);
exit;
?>
test.html
<a href='download-audio.php?file=duetsong.mp3'>Download Duet song MP3</a>
<a href='download-audio.php?file=duetsong.mp4'>Download Duet song MP4</a>

Categories