Amanda Muñoz
Amanda Muñoz

Reputation: 1

readfile doesn't force download

I'm trying to force a download when opening a page in php using readfile, but it doesn't work. When I go to the url https://www.inbrax.cl/belong-gracias/?docsbelong=BELONG-DICCIONARIO-CAP-1.pdf it displays the error message: 'El archivo no existe.', but if I console.log $fileName and $filePath it shows the correct information. It just doesn't execute the download.

I'm only starting to use php so I'm not sure what's the error.

I've tried adjusting the headers and changing the path but it hasn't worked yet.

Here's my code:

<?php
if(!empty($_GET['docsbelong'])){ 
    // Define file name and path 
    $fileName = basename($_GET['docsbelong']); 
    $filePath = './pdf/'.$fileName;  
 
    if(!empty($fileName) && file_exists($filePath)){ 
        // Define headers 
        header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0"); 
        header("Content-Description: File Transfer"); 
        header("Content-Disposition: attachment; filename=\"$fileName\"");
        header("Content-Type: application/pdf"); 
        header("Content-Transfer-Encoding: binary"); 
         
        // Read the file 
        readfile($fileName); 
        exit; 
    }else{ 
        echo 'El archivo no existe.';
    } 
} 
?>

Upvotes: -2

Views: 157

Answers (1)

K J
K J

Reputation: 11739

You just need the URL in a web page, none of that non-working code. It's superfluous eye-candy to serving a download URL. You could add a static thumbnail of the cover as time better spent as just needing a second line of code.

enter image description here

<a href="https://www.inbrax.cl/docsbelong/BELONG-DICCIONARIO-CAP-1.pdf" download="BELONG-DICCIONARIO-CAP-1.pdf">Click here to Download and View,<br>or rightclick to Save As Download<br>BELONG-DICCIONARIO-CAP-1</a>

Upvotes: 0

Related Questions