Search code examples
phpdownloadreadfile

PHP Readfile() not working for me - maybe header problem?


I checked similar posts and here's the problem: a portion of my codes :

if($_GET['dl']) {

$file=$_GET['dl'];
$file="../../rep/".$file;

header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file) . "\"");

readfile($file);
exit;}

This code runs when user submit form and redirects on current PHP file. The result opens in browser rather than download. I checked a lot of other headers or modifications with no clue.

So I made a separated PHP file : download.php and paste the above code exactly on it. then redirect user to this new file And Problem solved! (File downloads without any problem)

So my question is what's the problem exactly?


Solution

  • Thanks from comments, the reason founded! I had started the PHP tag <?php from second line in the file like this:

    • ...
    • php tag start here <?php

    Perhaps first line considered as an output.removed first line and now download starts properly ;)