March 19, 2012

making files in the folder donwloadable using php or javascript

Question by Shrestha Sunil

I am trying to making files to be downloadable after clicking the link of the listed file. I am not getting idea how to make it possible. I have completed to list file using following scripts. Now I have to provide listed file to be downloadable after clicking the file name. Plz help…

$dir = 'd:/temp_file/voice/';
if (is_dir($dir)) {
 if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
    if($file != '.' && $file != '..')
        echo "filename: ".$file."<br />";
               // header('Content-type: audio/wav');

             //   header('Content-Disposition: attachment; filename="'.$dir.$file.'"');

              //  readfile($dir.$file);
    }
    closedir($dh);
 }
}

Answer by Starx

Files are already downloadable by default.

Create a php file, through which the file will be downloaded. For example: download.php Place the following codes on them.

 $filename = $_GET['filename']; 
 $dir = "../path/to/directory/"; //$dir = 'd:/temp_file/voice/';
 // ^ Use Relative links           ^ Not system dependent link as this
 if(is_file($dir.$filename)) {
    header('Content-type: audio/wav');
    header('Content-Disposition: attachment; filename="'.$dir.$file.'"');
    echo file_get_contents($dir.$file);
 }

Next link to this page as this

<a href="download.php?name=filename.jpg">Download FileName</a>

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!