Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2006
    Posts
    1,120

    Make All Files In A Directory Downloadable Using .htaccess

    I have a directory in my website that is full of different files which people can upload to and download from.

    What I want to do is make it so that if someone clicks a link to file that is located in that directory, the download box will appear prompting them to download the file regardless of what type of file it is (this includes php, html, jpg, etc) instead of executing the php script or displaying the image in the browser.

    Anyone got any idea's on how to do this?

    I assume this is best accomplished using .htaccess, but any other idea's would be welcome.

  2. #2
    Join Date
    Mar 2007
    Location
    UK
    Posts
    89
    You could do it with a couple of php scripts: index.php and download.php.

    index.php lists all of the files in the current directory and generates a link for each one that allows access to it via download.php.
    download.php outputs the headers to make the browser save the file,then spits out the file.

    This method would put more load on your server, but would allow you more control over things.


    eg index.php would output links along the lines of
    <a href="/download.php?file=bob.php">bob.php</a>


    download.php would check the $_GET['file'] parameter to ensure that the user is not trying to do something malicious, then force the browser to download the file using something along these lines:

    Taken from marro at email dot cz's comment at http://uk2.php.net/readfile:
    <?php
    function DownloadFile($file) { // $file = include path
    if(file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
    }

    }
    ?>
    This code could be improved, but you get the idea.

    If you go down this route, you *must* perform very careful checking of the user-supplied data. ie don't allow them to download anything outside of the current directory etc. otherwise this script could be used to download any files that apache has access to.

  3. #3
    Join Date
    Apr 2006
    Posts
    1,120
    Cheers for that, I'll have a look.

  4. #4
    Can do this with apache auto indexes;

    http://httpd.apache.org/docs/1.3/mod/mod_autoindex.html

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •