0

See my other QUESTION.

I've successfully set up a simple file transfer, but I've noticed that trying to echo anything on the page corrupts the file, making it unopenable.

Here's the code:

$filename = $_GET['filename']; 
$dir = "C:/Users/Me/Desktop/"; 
$file = realpath($dir . $filename);   

//echo "$filename</br>$dir</br>$file";

if (file_exists($file)) {       
    header('Content-Disposition: attachment; filename="'.basename($file).'"');  
    header('Content-Type: application/octet-stream');    
    header('Content-Length: ' . filesize($file)); 
    readfile($file);
    exit;
}

This works just fine, but if I uncomment the echo, the downloaded file is corrupted and won't open.

Is this because, somehow, the echo is being written to the file to be downloaded? Perhaps (probably) I don't fully the process taking place above.

Obviously, the echo won't be displayed if the above code executes successfully anyway, but what other debugging practices would you recommend? Clearly, echoing variable values won't always work. Any alternatives?

Community
  • 1
  • 1
JEJoll
  • 547
  • 1
  • 6
  • 20
  • http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php > Output buffering as workaround – Federkun Apr 08 '16 at 15:50
  • 1
    Yes, your page sends HTTP protocol data to the browser describing what its going to do (i have a file for you, here is the file), the echo randomly interrupts this with random bytes corrupting the output as the browser cannot interpret what the server is telling it. – Alex K. Apr 08 '16 at 15:50
  • 1
    That is correct, the client receives the contents of the `$file`, echoing the text prepends the file with that string, corrupting it. To report that the file doesn't exist, you can write custom errors to the log using [error_log](http://php.net/manual/en/function.error-log.php) or you can [throw an exception](http://php.net/manual/en/language.exceptions.php) to handle errors your own way. – Egg Apr 08 '16 at 15:53

1 Answers1

1

Yes, if you echo some data it will become part of whatever file you are sending and probably corrupt it.

I would recommend you look at the error_log function. It will let you write to a log file, which won't affect output. You can look that the log periodically and check for any important errors.

Chris
  • 5,571
  • 2
  • 20
  • 32