简体   繁体   English

PHP:强制PDF文件下载

[英]PHP : Force PDF file to download

i am trying to download a . 我想下载一个。 pdf file on button submit, following is my code 按钮提交的pdf文件,以下是我的代码

if(mail('myemail@gmail.com', 'Brochure Downloaded ', $string)){ 
            $text= 'Your message recieved, We will contact you shrtly '; 
            $file_url = 'http://www.website.com/brochure.pdf'; 
                header('Content-Type: application/octet-stream');
                header("Content-Transfer-Encoding: Binary"); 
                header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
                readfile($file_url); // do the double-download-dance (dirty but worky)
    }

Now whats happening is that email is sent but files is not downloaded, instead page gets reloading and long characters are printed on the screen , 现在发生的事情是发送电子邮件但是没有下载文件,而是重新加载页面并在屏幕上打印长字符,

Need your help with this please 需要你的帮助

this is what i get 这就是我得到的 在此输入图像描述

I have changed headers a little bit. 我已经改变了一些标题。 I think the proper content type is application/pdf andsome of headers are not necessery. 我认为正确的内容类型是application/pdf并且一些标题不是必需的。

if(mail('myemail@gmail.com', 'Brochure Downloaded ', $string)){ 
  $text= 'Your message recieved, We will contact you shrtly '; 
  $file_url = 'http://www.website.com/brochure.pdf'; 
  header("Content-type:application/pdf");
  header("Content-Disposition:attachment;filename='" . basename($file_url) . "'");
  readfile($file_url); // do the double-download-dance (dirty but worky)
}

You may also add the content length: 您还可以添加内容长度:

header('Content-Length: ' . filesize($file_url));

check this code, first you need to add content type if you download any type file as like if you want to download image then header('Content-Type: image/png'); 检查此代码,如果要下载任何类型文件,首先需要添加内容类型,如果要下载图像然后标题('Content-Type:image / png'); if pdf then header("Content-Type: application/pdf"); if pdf then header(“Content-Type:application / pdf”); etc 等等

<?php
if (mail('myemail@gmail.com', 'Brochure Downloaded ', $string)) {
$text = 'Your message recieved, We will contact you shrtly ';
$file_url = 'http://www.website.com/brochure.pdf';
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file_url");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
readfile($file);
}
?>

you may use 你可以用

header('Content-Length: ' . filesize($file_url));

you should use Content-Length if you want someone download a file with another header 如果您希望有人下载带有另一个标题的文件,您应该使用Content-Length

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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