Home  >  Article  >  Backend Development  >  How to open a PDF file in a web browser using PHP?

How to open a PDF file in a web browser using PHP?

藏色散人
藏色散人Original
2019-03-18 10:51:339120browse

PHP uses standard code to display pdf files in web browsers. The process of displaying a PDF file involves the location of the PDF file on the server. It uses various types of header files to define the content composition in the form of type, configuration, transfer encoding, etc.

PHP passes the PDF file to read it on the browser. The browser either displays it or downloads it from the localhost server and then displays the pdf.

Note: PHP does not actually read PDF files. It does not recognize files in pdf format. It just passes the PDF file to the browser for reading in the browser. If you copy the pdf file into XAMPP's htdocs folder, you don't need to specify the file path.

Example 1:

Display pdf files on the browser.

<?php 
  
// 将文件名存储到变量中
$file = &#39;filename.pdf&#39;; 
$filename = &#39;filename.pdf&#39;; 
 
header(&#39;Content-type: application/pdf&#39;); 
  
header(&#39;Content-Disposition: inline; filename="&#39; . $filename . &#39;"&#39;); 
  
header(&#39;Content-Transfer-Encoding: binary&#39;); 
  
header(&#39;Accept-Ranges: bytes&#39;); 
  
// 读取文件
@readfile($file);

Output:

How to open a PDF file in a web browser using PHP?

Example 2:

<?php 
  
// PDF文件在服务器上的位置
$filename = "/path/to/the/file.pdf"; 
  
// Header content type 
header("Content-type: application/pdf"); 
  
header("Content-Length: " . filesize($filename)); 
  
// 将文件发送到浏览器。
readfile($filename);

Output:

How to open a PDF file in a web browser using PHP?

Recommended related video tutorials: "PHP Tutorial"

This article is about how to use PHP to open PDF files in a web browser. Simple and easy to understand, I hope it will be helpful to friends in need!

The above is the detailed content of How to open a PDF file in a web browser using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn