-1

Note: I have tried to implement the solutions provided in : How to fix "Headers already sent" error in PHP and it didnot help so I have posted this question. I have gone through various posts on similar problem but none of the solutions worked. Following is my code:

<form role="form" method="POST">
 <input type="submit" name="dff" id="dff" class="btn btn-default" value="Download Franchisee Form"></input>
</form>
<?php
 if(isset($_POST['dff']))
 {
  $yourfile="MyFile.pdf";
  $fp = @fopen($yourfile, 'rb');
  if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
  {
    header('Content-Type: "application/octet-stream"');
    header('Content-Disposition: attachment; filename="yourname.file"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header("Content-Transfer-Encoding: binary");
    header('Pragma: public');
    header("Content-Length: ".filesize($yourfile));
  }
  else
  {
    header('Content-Type: "application/octet-stream"');
    header('Content-Disposition: attachment; filename="yourname.file"');
    header("Content-Transfer-Encoding: binary");
    header('Expires: 0');
    header('Pragma: no-cache');
    header("Content-Length: ".filesize($yourfile));
  }
  fpassthru($fp);
  fclose($fp);
 }
?>

I get following errors on clicking this button:

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\GoogleKids\Franchisee.php:116) in C:\xampp\htdocs\GoogleKids\Franchisee.php on line 133

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\GoogleKids\Franchisee.php:116) in C:\xampp\htdocs\GoogleKids\Franchisee.php on line 134

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\GoogleKids\Franchisee.php:116) in C:\xampp\htdocs\GoogleKids\Franchisee.php on line 135

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\GoogleKids\Franchisee.php:116) in C:\xampp\htdocs\GoogleKids\Franchisee.php on line 136

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\GoogleKids\Franchisee.php:116) in C:\xampp\htdocs\GoogleKids\Franchisee.php on line 137

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\GoogleKids\Franchisee.php:116) in C:\xampp\htdocs\GoogleKids\Franchisee.php on line 138

and after that, I get unreadable symbols on the web page something like below:

%PDF-1.5 %���� 1 0 obj <> endobj 2 0 obj <> endobj 3 0 obj <>/ExtGState<>/Font<>/ProcSet[/PDF/Text/ImageB/ImageC/ImageI] >>/MediaBox[ 0 0 595.32 841.92] /Contents 7 0 R/Group<>/Tabs/S>> endobj 4 0 obj <> stream ����JFIF``��ZExifMM*JQQ�Q�������C    !(!0*21/*.-4;K@48G9-.BYBGNPTUT3?]c\RbKSTQ��C''Q6.6QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ��d9"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz����

Note: Even I used ob_start() and ob_flush() at the beginning and end of the script respectively, still i got the same error.

Note: I have not used any other PHP script on complete page. This is the only script. However, I do have another form tag that links to another webpage on performing action and it has its own separate submit button with a unique name and id. Please help.

Community
  • 1
  • 1
ITSagar
  • 673
  • 2
  • 10
  • 29
  • 1
    Possible duplicate of [How to fix "Headers already sent" error in PHP](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – Ivar Oct 13 '16 at 10:53
  • You cannot output anything BEFORE changing the header of a webpage – rak007 Oct 13 '16 at 10:54
  • If you want to set a header you MUST do it before you output anything. This includes `echo` or anything ouside of the `` tags. You are outputting your form before you set the header, so you get this error. Move the form to the bottom of the page and it will work. – Ivar Oct 13 '16 at 10:57
  • So, did you try with ob_flush? and set it correctly? You aren't really demonstrating or explaining "why" the answers in the duplicate question doesn't help you. – Epodax Oct 13 '16 at 10:59
  • yeah, i tried ob_start() and ob_flush(), it also gave the same error. And i cannot put the form to the bottom of page because i need to put the download link in the middle of the page where its relevant section exists. – ITSagar Oct 13 '16 at 11:38

2 Answers2

1

Try the following solution: On your web page, remove form tag and use an anchor as below:

<a href="downloads.php?download_file=MyFile.pdf">Download The File</a>

Then, create a new file named downloads.php and write the following code:

<?php
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script

$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $dl_file;

if ($fd = fopen ($fullPath, "r")) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "pdf":
        header("Content-type: application/pdf");
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
        break;
        // add more headers for other content types here
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
        break;
    }
    header("Content-length: $fsize");
    header("Cache-control: private"); //use this to open files directly
    while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
    }
}
fclose ($fd);
exit;
?>

I tested this code, it worked perfect for me in Chrome as well as IE. Make sure you change the file name and the file path according to your requirements. Don't forget to vote if this helps you.

Shobhit Gupta
  • 690
  • 4
  • 13
  • Hey, I had a quick implementation of this code with minor changes, and it worked like a charm.Seriously the solution is perfect and easy to implement. Thanks a lot for the solution. I started feeling that people here only care to criticise by down voting instead of trying to resolve the problem but you saved my day. Thanks bro. – ITSagar Oct 13 '16 at 13:22
0

You have...

<html><?php
    header('...');
?>

You want...

<?php
    header('...');
?><html>

The only code that may occur before a PHP header(...) call is more PHP (or any server-side code), not HTML, CSS, or plaintext. For the server to send any content, it must send the headers, and once sent, they cannot be resent. So, you must set the headers before sending content.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133