This problem is different of the other question problem. That problem was about IF condition. But this problem, instead of downloading file, it is printing on next page. Please don't confuse this question with others.
I have wrote a script which download output of text box. This script works fine on local server, it download the file successfully but when I put script on live server, the download file does not work. When download output button is clicked, instead of downloading file the output of page is shown on next page.
See live script here: http://www.globalitsoft.net/scripts/test.php
Here is the code of script:
<?php
error_reporting(0);
$mytext = "";
$txt = preg_replace('/\n+/', "\n", trim($_POST['inputtext']));
$text = explode("\n", $txt);
$output = array();
if(isset($_POST["submit"]) || isset($_POST["download"]) ) {
for($i=0;$i<count($text);$i++) {
$output[] .= trim($text[$i]) . ' AAAAA'.PHP_EOL;
}
}
if(isset($_POST["download"]) ) {
ob_clean();
$filename = "file-name-" .date('mdY-His'). '.txt';
$handle = fopen('php://output', "w");
fwrite($handle, implode($output));
fclose($handle);
header('Content-Description: File Transfer');
header("Content-type: application/force-download");
header("Content-Type: application/octet-stream charset=utf-8");
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . strlen(implode($output)));
readfile($filename);
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>
This works for me:
$handle = fopen("file.txt", "w");
fwrite($handle, "text1.....");
fclose($handle);
header('Content-Type: application/octet-stream');
//You dont need to enclose the filename value in quotes
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
Mysql run more than once while i try to download with download manager.
if(isset($_POST["fname"]) && isset($_SESSION['token']) && $_POST["token"] == $_SESSION['token']){
// after submit it runs two times
$sql = "INSERT INTO testpage SET
username = 'test',
name = 'xyz'
";
if(!mysqli_query($db_conx, $sql)){
echo mysqli_error($db_conx);
exit;
}
$fullPath = 'user/pdf/xyz.pdf';//let the path is this
$basefile_name = "abcd" ;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($basefile_name.".pdf"));
header('Content-Transfer-Encoding: binary');
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache");
header('Expires: 0');
header('Content-Length: ' . filesize($fullPath));
ob_clean();
flush();
readfile($fullPath);
exit;
}
if (function_exists('mcrypt_create_iv')) {
$token = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
} else {
$token = bin2hex(openssl_random_pseudo_bytes(32));
}
$_SESSION['token'] = $token;
and the html part is
<div class="container">
<form method="post">
First name: <input type="text" name="fname"><br><br>
Last name: <input type="text" name="lname"><br>
<input type="hidden" name="token" value="<?php echo $token; ?>">
<input type="submit" value="Submit">
</form>
</div>
Still have problen even after adding token where i am wrong .
thanx in advance . php mysql.
I have a problem with my .csv. So I tried to generate a .csv from an array using php. In the view I have :
<form id="form_logistique" action="myroute" method="post">
<div class="form-group " style="float: left;">
<label class="control-label" for="" style="display: inline-block; padding-right: 20px;">Date min</label>
<input type="text" id="date_min" name="date_min.name" value="date_min" placeholder="Date min" class="form-control datepicker" />
</div>
<div class="form-group" style="float: left;padding-left: 20px;">
<label class="control-label" for="" style="display: inline-block; padding-right: 20px;">Date max</label>
<input type="text" id="date_max" name="date_max" value="{{ date_max" placeholder="Date max" class="form-control datepicker" />
</div>
<input type="submit" class="btn btn-primary" style="margin-top: 25px;margin-left: 20px;" value="Rechercher"></input>
<input type="submit" class="btn btn-succes" style="margin-top: 25px;margin-left: 20px;" name="export" value="Exporter"></input>
</form>
In php :
public function getLogistique()
{
$this->form_logistique = new Form\Form(
new Form\Field\Text('date_min', '', true),
new Form\Field\Text('date_max','',true),
);
$date_min = '';
$date_max = '';
if ($this->getRequest()->isPostMethod() && $this->form_logistique->bind($_POST)){
$date_min = $this->form_logistique->date_min->getValue();
$date_max = $this->form_logistique->date_max->getValue();
}
$interdit = array(";", ",", ":", "*", "/", "|", "?", '"', "<", ">", "!", "_", "#", "[", "]", "\\", "{", "}", "~");
$aGifts = Gain::getGiftForLogistique($date_min, $date_max, $statut);
foreach($aGifts as $gift){
$date = explode(' ', $gift['date_gain']);
$gift['ref_article'] = $gift['ref_article'];
$gift['nom'] = str_replace($interdit,"",$gift['nom']);
$gift['prenom'] = str_replace($interdit,"",$gift['prenom']);
$gift['pseudo'] = $gift['pseudo'];
$gift['numero'] = trim(str_replace(";",",",str_replace("\\"," ",$gift['numero'])));
$gift['rue'] = str_replace($interdit,"",$gift['rue']);
$gift['complement'] = str_replace($interdit,"",$gift['complement']);
$gift['code_postal'] = $gift['code_postal'];
$gift['ville'] = str_replace(";",",",str_replace("\\"," ",$gift['ville']));
$gift['pays'] = $gift['pays'];
$gift['email'] = Gain::getEmailByIdm($gift['pseudo']);
$gift['tel'] = str_replace(";",",",str_replace("\\"," ",$gift['tel']));
$gift['id_instant_gagnant'] = $gift['id_instant_gagnant'];
$gift['date_gain'] = $date[0];
$aFilterGifts[] = $gift;
}
$this->aFilterGifts = $aFilterGifts;
if (isset($_POST['export'])) {
$output = fopen('php://output', 'w');
$sFileName = 'Fichier_de_logistique.csv';
header('Content-Disposition: attachement; filename="' . $sFileName . '";');
header('Content-Type: application/download');
fwrite($output, "sep=;\n");
fputcsv($output, array(''Nom', 'Prenom'), ";");
foreach ($aFilterGifts as $value) {
fputcsv($output, $value, ";");
}
fpassthru($output);
fclose($output);
}
return $this->render('template/customer_service/member/logistique.twig');
}
The .csv is generated, but the problem is that after the array in .csv I have all content .html of page and I don't understand where is the problem.Please help me! Thx in advance
The problem problem lies here:
if (isset($_POST['export'])) {
$output = fopen('php://output', 'w');
$sFileName = 'Fichier_de_logistique.csv';
header('Content-Disposition: attachement; filename="' . $sFileName . '";');
header('Content-Type: application/download');
fwrite($output, "sep=;\n");
fputcsv($output, array('Nom', 'Prenom'), ";");
foreach ($aFilterGifts as $value) {
fputcsv($output, $value, ";");
}
fpassthru($output);
fclose($output);
}
return $this->render('template/customer_service/member/logistique.twig');
The function writes headers and the content of the CSV file to STDOUT (php://output), but then the whole circus goes on. This function returns content of a template to it's parent function and this probably renderes it to STDOUT as well (using echo, print or something else). The easiest thing to do here (but not the correct) would be to put die(); after fclose($output);:
if (isset($_POST['export'])) {
$output = fopen('php://output', 'w');
$sFileName = 'Fichier_de_logistique.csv';
header('Content-Disposition: attachement; filename="' . $sFileName . '";');
header('Content-Type: application/download');
fwrite($output, "sep=;\n");
fputcsv($output, array('Nom', 'Prenom'), ";");
foreach ($aFilterGifts as $value) {
fputcsv($output, $value, ";");
}
fpassthru($output);
fclose($output);
die();
}
return $this->render('template/customer_service/member/logistique.twig');
The correct way in my opinion is to create a new route and controller action for CSV exports, that has no HTML output.
Your question isn't very clear, but it may be you want to terminate the execution of the script after the fclose().
its because at some point in the code you may have echo or print something. A better approach would be to write the csv to a file. And then send that file as Content-Disposition: attachment. Like in the code below where file is the path of file.
if (file_exists($file)) {
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;
}
fputcsv($output, array(''Nom', 'Prenom'), ";");
typo here - double single quote before Nom.
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>
I have the following form:
<form action="download.php" method="get">
<input type="checkbox" name="file1" /> File1 <br/>
<input type="checkbox" name="file2" /> File2 <br/>
<input type="checkbox" name="file3" /> File3 <br/>
<input type="checkbox" name="file4" /> File4 <br/>
<input type="checkbox" name="file5" /> File5 <br/>
<input type="submit" name="mysubmit" value="Download!">
</form>
I cant then GET the ticked value:
<?php echo $_GET["file1"]; ?>
Gives the result: on
However want I want to be able to do is select those options, and each option relates to a PHP file, on Submit each file is combiled into a ZIP
Any help appreciated.
First, add a value field to your form fields and change them to an array:
<form action="download.php" method="get">
<input type="checkbox" name="file[0]" value="1" /> File1 <br/>
<input type="checkbox" name="file[1]" value="1" /> File2 <br/>
<input type="checkbox" name="file[2]" value="1" /> File3 <br/>
<input type="checkbox" name="file[3]" value="1" /> File4 <br/>
<input type="checkbox" name="file[4]" value="1" /> File5 <br/>
<input type="submit" name="mysubmit" value="Download!">
</form>
Next, in download.php:
if (!empty($_POST['file'])) {
// open zip
$zip_path = '/path/to/created/download.zip';
$zip = new ZipArchive();
if ($zip->open($zip_path, ZIPARCHIVE::CREATE) !== TRUE) {
die ("An error occurred creating your ZIP file.");
}
// checkbox values dont matter because only checked boxes show up in POST data
foreach ($_POST['file'] as $key => $val) {
// generate filename to add to zip
$filename = '/path/to/php/file' . $key . '.php';
$zip->addFile($filename) or die ("ERROR: Could not add the file $filename");
}
$zip->close();
//===============
// force download
//===============
// assume you have a full path to file stored in $zip_path
if (!is_file($zip_path)) {
die('The file appears to be invalid.');
}
$zip_path = str_replace('\\', '/', realpath($zip_path));
$filesize = filesize($zip_path);
$filename = substr(strrchr('/'.$zip_path, '/'), 1);
$extension = strtolower(substr(strrchr($zip_path, '.'), 1));
// use this unless you want to find the mime type based on extension
$mime = array('application/octet-stream');
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.sprintf('%d', $filesize));
header('Expires: 0');
// check for IE only headers
if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))) {
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
} else {
header('Pragma: no-cache');
}
$handle = fopen($filepath, 'rb');
fpassthru($handle);
fclose($handle);
} // close $_POST check
You can use isset($_FILES['file1']) to check if file1 is uploaded
Loop from file1 to file5
Save files from temporary paths to permanent ones
Zip them using http://php.net/manual/en/book.zip.php & http://php.net/manual/en/ref.zip.php
Optional: Delete the uploaded files (using unlink)
Force download the zip file to the browser. See this: http://php.net/manual/en/function.header.php
It's quite simple. Enjoy!