Download a file from a folder on a server via php


I have this table in php and I want to press the Folio Num to download the file ".xls" from the server with the name according to its Folio for example, "If I press the folio 130, I have to download the file 130 .xls "

This is my code:

foreach ($query as $valor) { 
    echo '<tr> <td nowrap style="width: 200px; text-align:center;"><a target="_self" href="javascript:SelCalen(\''. $valor[0] .'\',\''. $valor[2] .'\',\''. $v01 .'\');" >' . $valor[0] . '</a></td> <td style="width: 100px;" nowrap class="center">' . $valor[1] . '</td> <td nowrap style="width: 200px; text-align:left;">' . $valor[2] . '</td> <td nowrap class="center"> ' .$valor[3] . '</td> <td nowrap class="center">' . $valor[4] . '</td> </tr>'; 

echo '</tbody>';

And this I have to download the .xls

// Definimos el nombre de archivo a descargar. 
$filename = "100.xls"; 

// Ahora guardamos otra variable con la ruta del archivo 
$file = "functions/".$filename; 

// Aquí, establecemos la cabecera del documento 
header("Content-Description: Descargar imagen"); 
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/force-download"); 
header("Content-Length: " . filesize($file)); 
header("Content-Transfer-Encoding: binary"); 

asked by Aruro deGyy 29.07.2016 в 22:01

2 answers


I think it would be easier to give your a the default behavior, letting your href have the URL of the file to download.

You would only have to pass the Javascript function that you use in a to your container; everything would be more or less like (without trying):

foreach($query as $valor){
    $sFila = <<<FILA
        <td nowrap style="width: 200px; text-align:center;" onclick="SelCalen('{$valor[0]}','{$valor[2]}','{$v01}');">
            <a target="_self" href="http://tudominio.tld/ruta_del_fichero/{$valor[0]}.xls" >{$valor[0]}</a>
        <td style="width: 100px;" nowrap class="center">{$valor[1]}</td>
        <td nowrap style="width: 200px; text-align:left;">{$valor[2]}</td>
        <td nowrap class="center"> {$valor[3]}</td>
        <td nowrap class="center">{$valor[4]}</td>
    echo $sFila;

I have changed it to heredoc to improve reading, but it should work the same as you put it.

One last thing: you have at the end of the call SelCalen a variable $v01 that I do not know if it is external to the loop or a confusion.

I would do it non-obstrusively, but that's another matter;)

answered by 28.09.2016 в 12:46

I think you should put the path of the files in bd and then just select them from the download php and ready the downloads and the only thing you recover is the id of the table

answered by 29.08.2016 в 04:34