Uploading PDF Files in PHP: A Simple Guide

Estimated read time 2 min read

Introduction

Uploading PDF files is a common functionality in web applications, allowing users to share and manage documents. In this guide, we’ll go through the process of creating a PHP script to handle the upload of PDF files.

1. Create HTML Form for File Upload

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF Upload</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="pdf" accept=".pdf">
        <button type="submit" name="submit">Upload PDF</button>
    </form>
</body>
</html>

This HTML form includes an input field with the accept attribute set to “.pdf” to ensure that only PDF files can be selected. The form’s enctype attribute is set to “multipart/form-data” to support file uploads.

2. Create PHP Script to Handle Upload

<?php
if (isset($_POST['submit'])) {
    $uploadDir = 'pdfs/';
    $pdfName = $_FILES['pdf']['name'];
    $pdfTmp = $_FILES['pdf']['tmp_name'];

    $targetPath = $uploadDir . $pdfName;

    if (move_uploaded_file($pdfTmp, $targetPath)) {
        echo "PDF uploaded successfully: " . $pdfName;
    } else {
        echo "Failed to upload PDF.";
    }
}
?>

This PHP script checks if the form is submitted, moves the uploaded PDF file to the specified upload directory, and echoes a success or failure message.

3. Ensure Proper Permissions

Make sure the ‘pdfs’ directory has the necessary permissions to allow file uploads. You can set the permissions using the following command in a terminal:

chmod -R 755 pdfs/

4. Display Uploaded PDF

To display the uploaded PDF or provide a download link, you can create another PHP script or modify the existing one:

<?php
$uploadDir = 'pdfs/';
$pdfName = $_FILES['pdf']['name'];

echo '<a href="' . $uploadDir . $pdfName . '" target="_blank">View PDF</a>';
?>

This script generates an anchor link (<a>) that allows users to view the uploaded PDF in a new tab or download it.

With these steps, you’ve created a basic system for uploading and displaying PDF files using PHP. Depending on your requirements, you can enhance this setup by adding features such as file validation, size restrictions, or integrating with a database to keep track of uploaded PDFs.

Related Articles