Solution Listing Files by ID of a Table
I imagine you have a chart or a way to make one from/to file ID for its respective path (path).
Let’s assume you have the table with the fields ID
and CAMINHO
, thus:
ID NOME
1 /arquivos/planilha.xls
2 /arquivos/documento.pdf
And on the page you have manage to list the files like this:
<a href="download.php?id=1">planilha.xls</a>
<a href="download.php?id=2">documento</a>
So in the script download.php
you need to make a logic like this:
$id_arquivo = $_GET['id'];
$caminho = recuperaCaminhoPorId($id_arquivo); //implementar esta função em algum lugar
readfile($caminho); //lê o arquivo e manda para o usuário
Obviously it is good for you to do some treatments, such as when the script does not receive any parameter or does not find the ID in the database.
See the job documentation readfile()
.
If you want to force the download of files that by default would be opened in the browser (HTML, text, image, etc.), you can also put headers, such as:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($caminho));
Note that headers need to be set before writing the file, i.e., before calling the function readfile();
.
Solution with direct link to the file
After seeing the question update, it was clear that the downloadable files are in a folder available on the HTTP server.
To make the file available, you can create a link with the path relative to the server root.
<a href="/interno/2014/01/30/1391088944.2621-11_35_44-4002-1006.WAV">Download</a>
If you want to list the files of a folder using PHP and create the links automatically, you can use the function scandir()
PHP to list the files and make a for
to print the links.
Example:
$files = scandir($dir);
$basedir = '/var/www/html';
foreach($files as $f) {
if($f != '.' && $f != '..') {
echo '<a href="' . str_replace($basedir,'',$f) . '">'
. basename($f) . '</a>';
}
}
This is just a simple idea that you can adapt to your need.
And what exactly is the problem? Gives error page? File not found? Opens in browser instead of downloading?
– bfavaretto
I have a system in php, in it brings a table that one of the columns is several ID that when clicking on it, it downloads a file referring to the ID. The file is on a Centos Linux server
– Haone Nakano
Do you know the file path on the server? Is it accessible to the web server? Please use the [Edit] link above to include this information in the question itself.
– bfavaretto