douzhang1364
douzhang1364
2017-05-18 11:51

Php文本框输出是打印而不是下载

  • download
  • php

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('/
+/', "
", trim($_POST['inputtext']));
    $text = explode("
", $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>
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答