Hello guys, I want to create download file script, I used an id to refer to a file in my site
here is the script
get the id and search in database for filename then return it for download.

<?php
if ($_GET['file']) {
$id = (int)$_GET['file'];
$sql= "SELECT filename FROM uploads WHERE id = $id LIMIT 1";
$run = mysql_query($sql);
$data = mysql_fetch_assoc($run);
// Define the path to file
$file = 'uploads/'.$data['filename'];
 if(!file_exists($file))
 {
     // File doesn't exist, output error
     die('<div class="row-fluid"><span class="label label-important"><h1>File Not Found</h1></span></div>');
 }
 else
 {
     header("Cache-Control: public");
     header("Content-Description: File Transfer");
     header("Content-Disposition: attachment; filename=".$file);
     header("Content-Type: application/force-download");
     header("Content-Transfer-Encoding: binary");
     // Read the file from disk
     readfile($file);
     exit();
 }
}else {
echo ('<div class="row-fluid"><span class="label label-important"><h1>No File Chosen</h1></span></div>');
}
?>

and here is the results

ed0b2968bf49f4928c65c31ce012c54a

what should I do ?

Recommended Answers

All 6 Replies

Try this, in your case the problem is that you echo something already.
And you must give an extension to the Content-Type:

Try this version.

     function download($file)
     {
       $dir = "downloads/";
       $path = $dir.$file;

       if(!file_exists($path))
       {
         die('Error : fisierul cautat nu exista!');
       }
       else
       {
         header("Cache-Control: public");
         header("Content-Description: File Transfer");
         header("Content-Disposition: attachment; filename=$path");
         header("Content-Type: application/rar");
         header("Content-Transfer-Encoding: binary");

         readfile($path);
       }
     }

     if(isset($_GET['download']))
     {
       if(!empty($_GET['download']))
       {
         $file = $_GET['download'];
         download($file);
       }
     }

All you have to do is to call a download link.

<a href="index.php?download=yourFile.rar">Download</a>

Is that all code there is? Perhaps you have something before <?php causing this.

as pritaeas says check before <?php may be you have any white space there remove it this can solve your problem

I have

<?php
include ('include/config.php');
include ('include/functions.php');
?>

So perhaps something is outputted in one of those includes, or maybe a BOM marker is causing this.

Ok then I should edit those files so nothing is outputed
OK thanks for the tips

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.