0

This is my first time trying to send a file to the user using php and I have the following setup:

if (file_exists($fullPath)) {

    header('Content-type: text/csv');
    //Use Content-Disposition: attachment to specify the filename
    header('Content-Disposition: attachment; filename='.basename($fullPath));
    //No cache
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    //Define file size
    header('Content-Length: ' . filesize($fullPath));

    ob_clean();
    flush();
    readfile($fullPath);
}else{
    echo "alert(\"File name is NOT FOUND: ".$fullPath."\");";
}

This does grab the file but it displays the file on the webpage as if I echo-ed the file contents. The script that holds this code is included with a require statement. If I manually call this single file by navigating to it through the browser, the file gets downloaded but If this script is included as a required statement within another script, then the file is not downloaded but just outputted to the screen.

My suspicion is that there may be some issue with the headers but I am not sure if that's the issue.

Georgi Angelov
  • 4,338
  • 12
  • 67
  • 96
  • I have the same suspicion. What does the containing PHP code do? If the container is *nothing but* the require statement, does the problem persist? – David Jul 06 '17 at 21:16
  • `error_reporting(E_ALL); ini_set('display_errors', '1');` should reveal all. – AbraCadaver Jul 06 '17 at 21:18
  • 2
    Try something like `header('Content-type: application/octet-stream')` – Kisaragi Jul 06 '17 at 21:19
  • Check your log to see there's a "Headers already sent" warning. – Barmar Jul 06 '17 at 21:20
  • Does your other script, that you include this in, output anything? – M. Eriksson Jul 06 '17 at 21:20
  • Is this included in a template, inside ` – M. Eriksson Jul 06 '17 at 21:22
  • I see you're calling `ob_clean()`. Does the calling script use `ob_start()`? – Barmar Jul 06 '17 at 21:24
  • @David, if I create just a plain container script that requires the downloader code, then the file is being downloaded. I just checked the headers in both instances( my normal wrapper code and the plain wrapper ) and they are indeed different. That being said, the headers on my real code have content type of "application/x-www-form-urlencoded". It seems the headers are already set and I can't really change them. – Georgi Angelov Jul 06 '17 at 22:10
  • Would you please show the contents of the file that `require()`s this script? ... Or at least the lines up to and including the line where it is required? – J. Allan Jul 06 '17 at 23:32

0 Answers0