简体   繁体   中英

Start download PDF file automatically

I want to download PDF file automatically. It is downloading but it is giving "Failed to load PDF document."

$select = "SELECT * FROM `success-stories` where id='$id'";
       $result = $conn->query($select);
       $row = $result->fetch_assoc();
       $file=$row["download_pdf"];
       $file_arr=explode("/",$file);
       $path=$file_arr[0]."/".$file_arr[1]."/".$file_arr[2];
       $pdf_file=$file_arr[2];
      //  echo $file."<br/>";
      //  print_r($path);
      //  die;
       if(file_exists($path))
       {
        header("Content-disposition: attachment; filename=".$path."");
        header("Content-type: application/pdf");
        readfile($path);
       } 

Change

header("Content-disposition: attachment; filename=".$path."");

to

header('Content-disposition: attachment; filename="'.basename($path).'"');

As mentioned by @kmoser in the comments, as a safety measure, you can do htmlentities() on the basename() if you are actually saving the uploaded file as is with the same name. So it would look like:

header('Content-disposition: attachment; filename="'.htmlentities(basename($path)).'"');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM