I have a URL where I save some projects from my work, they are mostly MDB files, but some JPG and PDF are there too.
What I need to do is to list every file from that directory (already done) and give the user the option to download it.
How is that achieved using PHP?
If the server is configured correctly, you cannot download a PHP file. It will be executed when called via the webserver. The only way to see what it does is to gain access to the server via SSH or FTP or some other method.
'); } else { // Connect to the database $link=mysql_connect("localhost","*****","*****") or die(mysql_error()); mysql_select_db("RadReq", $link) or die(mysql_error()); mysql_set_charset('utf-8'); // Fetch the file information $query = "SELECT * FROM formdata WHERE form_id = $id"; $result=mysql_query($query); if($result ...
To read directory contents you can use readdir() and use a script, in my example download.php
, to download files
if ($handle = opendir('/path/to/your/dir/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
}
}
closedir($handle);
}
In download.php
you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php
$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;
if(!file_exists($file)){ // file does not exist
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile($file);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With