PHP File Download with Examples

Hey there! So, you want to learn how to handle file downloads using PHP? Awesome! Whether you're building a file-sharing platform, a document management system, or just want to let users download files from your server, PHP makes it pretty straightforward. Let’s dive in together, step by step, and I’ll walk you through everything you need to know. We’ll use PHP 8 for this, so make sure you’re up to date!

 

 

php file download with examples

 

 

Why Would You Need File Downloads in PHP?

 

Before we get into the code, let’s talk about why you might need this feature. Imagine you’re building a website where users can upload resumes, and employers can download them. Or maybe you’re creating a music-sharing site where users can download songs. In both cases, you’ll need a way to securely and efficiently serve files to users.

 

PHP makes it easy to handle file downloads, and with PHP 8, you get some nice performance improvements and cleaner syntax to work with. Let’s get started!

 

How File Downloads Work in PHP

 

When a user clicks a download link, the server sends the file to the browser with specific headers. These headers tell the browser to treat the response as a file download rather than displaying it in the browser. Here’s the basic flow:

 

  1. Set Headers: Tell the browser what kind of file it is and that it should be downloaded.
  2. Read the File: Use PHP to read the file from the server.
  3. Output the File: Send the file content to the browser.

 

Let’s break this down with an example.

 

Example 1: Basic File Download

 

Let’s say you have a file called example.pdf in a folder named uploads. You want users to be able to download it when they click a link.

 

Here’s how you can do it:

 

<?php
// File path
$file = 'uploads/example.pdf';

// Check if the file exists
if (file_exists($file)) {
    // Set headers
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

    // Read the file and output it to the browser
    readfile($file);
    exit;
} else {
    // If the file doesn't exist, show an error
    echo "File not found!";
}
?>

 

What’s Happening Here?

 

  1. Check if the file exists: We use file_exists() to make sure the file is there before trying to download it.
  2. Set headers: The header() function sends HTTP headers to the browser. The most important ones are:
    • Content-Type: Tells the browser what kind of file it is (e.g., PDF, image, etc.).
    • Content-Disposition: Tells the browser to download the file and suggests a filename.
    • Content-Length: Specifies the size of the file.
  3. Read and output the file: readfile() reads the file and sends it to the browser.

 

Example 2: Downloading Files Dynamically

 

What if you want to let users download files based on their input? For example, they type in a filename, and your script serves that file. Here’s how you can do it:

 

<?php
// Get the filename from the user (e.g., via a form or URL parameter)
$filename = $_GET['filename']; // Always sanitize user input in real-world apps!

// Define the folder where files are stored
$folder = 'uploads/';
$file = $folder . $filename;

// Check if the file exists
if (file_exists($file)) {
    // Set headers
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream'); // Generic file type
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

    // Read the file and output it to the browser
    readfile($file);
    exit;
} else {
    // If the file doesn't exist, show an error
    echo "File not found!";
}
?>

 

Key Points:

 

  • User Input: Always sanitize user input to prevent security issues like directory traversal attacks. For example, use basename() to ensure the user can’t access files outside the intended folder.
  • Generic Content-Type: We use application/octet-stream as a generic type for any file. You can dynamically set the correct type if needed.

 

Example 3: Forcing Downloads for Specific File Types

 

Sometimes, you might want to force a download for certain file types (like images) that would normally display in the browser. Here’s how you can do that:

 

<?php
$file = 'uploads/image.jpg';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: image/jpeg');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

    readfile($file);
    exit;
} else {
    echo "File not found!";
}
?>

 

What’s Different?

 

  • Content-Type: We set it to image/jpeg for a JPEG image. You can adjust this for other file types (e.g., image/png, application/zip, etc.).
  • Forced Download: Even though the browser could display the image, the Content-Disposition header forces it to download instead.

 

Example 4: Securing File Downloads

 

Security is super important when dealing with file downloads. You don’t want users downloading files they shouldn’t have access to. Here’s a simple way to secure your downloads:

 

<?php
// Check if the user is logged in (example)
session_start();
if (!isset($_SESSION['user_id'])) {
    die("Unauthorized access!");
}

$file = 'uploads/secret_document.pdf';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

    readfile($file);
    exit;
} else {
    echo "File not found!";
}
?>

 

Security Tips:

 

  • Authentication: Always check if the user is logged in or has permission to access the file.
  • Sanitize Input: If you’re using user input to determine the file, sanitize it to prevent attacks.
  • File Location: Store files outside the web root if possible, so they can’t be accessed directly via a URL.

 

Done!

 

And there you have it! You now know how to handle file downloads in PHP 8. Whether you’re serving PDFs, images, or any other file type, PHP makes it easy to get the job done. Just remember to:

  1. Set the right headers.
  2. Check if the file exists.
  3. Secure your downloads to prevent unauthorized access.
chandrakumar

Hi, Am Chandra Kumar, I have completed my graduation in B.E computer science and Engineering. I am the founder of Dailyaspirants and I have been doing blogging and website design and development .since 2018 and 8+experience gained in this field.

*

Post a Comment (0)
Previous Post Next Post