I host my website from my home server. I have downloa folder that constantly changes, is there a way to get the php file to automatically create download links everytime it is accessed?

Hi,

There are two php functions called "opendir" and "readdir". By using these functions, you can easily create a simple php script to generate download links for the files located in the directory you assigned.

For example, WARNING! script below is not tested, but I am confident this will work in the absensce of the any syntax errors.

<?php

function this_download($dir,$extension){
## use opendir please see referenced link above
if ($handle = opendir($dir)) {

## cycle items in the directory
 while (false !== ($entry = readdir($handle))) {
    ## get show only the file extension you want downloaded
    ## otherwise just remove this
    if(substr(strrchr($entry, '.'), 1) === $extension){

    ## generate the download link
    echo '<a href="'. $entry .'">Download This file</a>';
    }
}

}

to use the function above just supply the dir and the file extension you want the download link generated.

 ## sample usage
 $createDownloadLink = this_download('downloadDir', 'flv');

please read opendir and readdir as referenced above.

thank you, that works great. I tried adding the function the gets the file name but is not working:

<?php
INCLUDE 'index.php';

function this_download($dir,$extension){
## use opendir please see referenced link aboves
$dir2 = new DirectoryIterator(dirname(__FILE__));
$dir2= realpath('/downloads');
if ($handle = opendir($dir)) {

## cycle items in the directory
 while (false !== ($entry = readdir($handle))) {
    ## get show only the file extension you want downloaded
    ## otherwise just remove this
    if(substr(strrchr($entry, '.'), 1) === $extension){

    ## generate the download link
    foreach ($dir2 as $fileinfo) {


    echo '<a href="'. $entry .'" class="text">' .$fileinfo->getFilename(). '</a> <br />';
    }
    }
    }
}

}

 ## sample usage
 $createDownloadLink = this_download('downloads', 'zip');


?>

you can easily get the filename of the items $entry, by modifying the downlink link code like this

echo '<a href="'. $dir . $entry .'">'.preg_replace('/\.[^.]*$/', '', $entry) .'</a><br/>';

there are many ways of getting the filename without extension, but the above codes is the only one I come up of right now. e.g. basename, substr, str_replace will work also..

The advantage of using the auto-fill options in your browser is that it's already installed, so you don't need to do anything extra to use it. However, your browser auto-fill may not have as many features as other auto-fill programs.

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.