0

I have the following file.php. My PDF is in a files folder, file.php, and its file are in the same directory. When I press the button, the PDF is not downloading but the file.php is.

<?php
  if (isset($_POST['file_name'])){
    $file= $_POST['file_name'];
    header('Content- type: application/pdf');
    header('Content-Disposition: attachament; filename: " .$files"');
    readfile('files/'.$file);
    exit(); 
  }
?>
<form action="file.php" method="POST" >
  <input name="file_name" value="cv.pdf" type="hidden">
  <input type="submit" value="Download CV">
</form>
1
  • 2
    what is $files in header('Content-Disposition: attachament; filename: " .$files"'); ?
    – ArtOsi
    Commented Jul 20, 2017 at 7:56

3 Answers 3

5

No need of all that. Just try this:

<a href="/files/yourfullPathOnTheServer.format" download>

You can replace a href with button :)

2
  • This kind of removes any chance of adding server side logic to it doesn't like checking for authorisation.
    – apokryfos
    Commented Jul 20, 2017 at 7:56
  • In that case, You can submit via POST and get the full path in the reponse. And use window redirect in javascript to open the file in another window :)
    – informer
    Commented Jul 20, 2017 at 7:58
2

try with this if you want to download pdf using php code,set file path to $file

<?php
 $file = 'filename.pdf';
 if(!file){
     die('Error: file not found');
 }else{
     header("Cache-Control: public");
     header("Content-Description: File Transfer");
     header("Content-Disposition: attachment; filename=$file");
     header("Content-Type: application/pdf");
     header("Content-Transfer-Encoding: binary");
     readfile($file);
 }
 ?>
0

You need to just change the below code

header('Content-Disposition: attachament; filename: " .$files"');

with this:

header("Content-Disposition: attachament; filename: '$files'");

Also remember that

It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)

1
  • It's look like here is a space in your content-type , header('Content- type: application/pdf');. Remove space and try again. Commented Jul 20, 2017 at 8:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.