Open In App

How to read PDF file using PHP ?

Last Updated : 12 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how you can show/read PDF file contents on a browser using PHP.

We have to include an external PHP file named “class.pdf2text.php“. Include it in the required web page using PHP. Create an HTML form, in which we can choose a PDF file from your computer and also check whether its file extension is PDF or not.

Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this article, we will be using the XAMPP server.

Project folder structure and files:: Create a folder for your project and add class.pdf2text.php. Create a new index.php file. Keep your main project folder (for example.. example/pdf here) in the “C://xampp/htdocs/” if you are using XAMPP or “C://wamp64/www/” folder if you are using the WAMP server respectively. 

The folder structure should look like this:

folder structure

index.php: Below is the PHP source code for attaching the pdf file using HTML form and reading its content. Let us first understand the PHP part.

In the below code, the first if block verifies whether there is any file attached or not using the PHP isset() function. And the second if block verifies that the uploaded file is a PDF file. $_FILES is a two-dimensional superglobal associative array of items that are being uploaded via the HTTP POST method. Then we are instantiating the pdf2text() method in $a and finally return the contents of the pdf file.

In the HTML <form> tag, we are using “enctype=’multipart/form-data” which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form.

PHP




<?php
  
require('class.pdf2text.php');
extract($_POST);
 
if(isset($readpdf)){
     
    if($_FILES['file']['type']=="application/pdf") {
        $a = new PDF2Text();
        $a->setFilename($_FILES['file']['tmp_name']);
        $a->decodePDF();
        echo $a->output();
    }
      
    else {
        echo "<p style='color:red; text-align:center'>
            Wrong file format</p>
";
    }
}   
?>
 
<html>
 
<head>
    <title>Read pdf php</title>
</head>
 
<body>
    <form method="post" enctype="multipart/form-data">
        Choose Your File
        <input type="file" name="file" />
        <br>
        <input type="submit" value="Read PDF" name="readpdf" />
    </form>
</body>
 
</html>


Output: Finally, you should be able to read the contents of the PDF file on the browser.

read PDF file

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads