PHP: Open a file on the server for download?

2019-08-30 18:54发布

I have a PDF on my server. Now I want to open this file so the user can download it using the browser. How can I do that? I dont want to read the file or anything, its already on the server, just need to download it ...

Thanks?

4条回答
▲ chillily
2楼-- · 2019-08-30 19:08

there are differenct options:

First: if its in your htdocs folder, just link to it ( http://example.com/myfile.pdf )

Second: you could use the x-sendfile header. it is not supported by all servers. make sure to read the docs to find out what your server provides

third: you could set the appropriate header (Content-Type, Content-Length, etc) and then read the file via the readfile function

查看更多
Rolldiameter
3楼-- · 2019-08-30 19:08
$doc = 'path/to/doc.pdf';
header('Content-Disposition: attachment; filename="downloaded.pdf');
readfile($doc);

will be download as downloaded.pdf

查看更多
ゆ 、 Hurt°
4楼-- · 2019-08-30 19:10

If you are using apache server, you can add this code to your VirtualHost config, or to your .htaccess file:

<FilesMatch "\.(pdf|PDF)">
  ForceType application/pdf
  Header set Content-Disposition attachment
</FilesMatch>
查看更多
家丑人穷心不美
5楼-- · 2019-08-30 19:11

Please be more specific, is your server a web server? If so, you can simply add the pdf somewhere in your root directory and navigate to it directly in a web browser and it should automatically download.

ie http://whateveryoursiteis.com/testpdf.pdf

查看更多
登录 后发表回答