Download server document

2

I need to download a document from the base of the database, it is a pdf, but it is downloaded to me blank, can someone tell me what my code fails?

The sql is correct ....

$id = $_GET['id'];


$sql = "SELECT * FROM documents WHERE id='".$id."'";
$conect = new PDO("mysql:host=localhost;dbname=dbpruebas","root", "", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$resultado = $conect->query($sql);      
  if (isset($resultado)) {
        $fila = $resultado->fetch();
        if ($fila !== false) {

        $ruta = "./files/" . $fila['filepath'];
           header('Content-Type: application/force-download');
           header('Content-Disposition: attachment; filename=' . $fila['name'] . ".pdf" );
           header('Content-Transfer-Encoding: binary');
           header('Content-Length: ' . filesize($ruta) );
           readfile($ruta);

        }
    }
    
asked by AGD_12 26.03.2017 в 18:59
source

2 answers

0

I just tried this code on my website and it works for me.

A. DOWNLOAD DIRECTLY:

$archivo="https://www.boe.es/buscar/pdf/2013/BOE-A-2013-12886-consolidado.pdf";
header("Content-Length: " . filesize ($archivo) ); 
header("Content-type: application/pdf"); 
header("Content-disposition: attachment; filename=".basename($archivo));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
$filepath = readfile($archivo);

B. SHOW ONLINE

$archivo="https://www.boe.es/buscar/pdf/2013/BOE-A-2013-12886-consolidado.pdf";
header("Content-Length: " . filesize ($archivo) ); 
header("Content-type: application/pdf"); 
header("Content-disposition: inline;     
filename=".basename($archivo));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
$filepath = readfile($archivo);

NOTE:

For more clarity in the code, I have put the name of the file in a variable $archivo , it's your turn to capture in $archivo a complete and valid path of your pdf. In this case I used this example pdf: https://www.boe.es/buscar/pdf/2013/BOE-A-2013-12886-consolidado.pdf If you want you can try it on any php of your server.

I prefer the variables, since concatenating directly inside the code makes me nervous :) and sometimes things fail you because in the direct concatenation there is a comma of more or less, or a point of more or less.

    
answered by 27.03.2017 / 11:16
source
0

Test replacing this:

      header('Content-Type: application/force-download');
      header('Content-Disposition: attachment; filename=' . $fila['name'] . ".pdf" );
      header('Content-Transfer-Encoding: binary');
      header('Content-Length: ' . filesize($ruta) );
      readfile($ruta);

for this:

    header('Content-disposition: attachment; filename=' . $fila['name'] . ".pdf" );
    header("Content-type: application/pdf");
    readfile("$ruta");
    
answered by 27.03.2017 в 00:10