Current Location: Home> Latest Articles> Complete Guide to PHP File Download: readfile, header, and cURL Examples

Complete Guide to PHP File Download: readfile, header, and cURL Examples

M66 2025-10-28

Methods for Downloading Files in PHP

There are several ways to download files in PHP. Depending on your needs, you can choose the most suitable method. Common approaches include using the readfile() function for direct download, using the header() function to force browser download, and using the cURL library to download remote files.

Direct Download with readfile()

The simplest way to download a file is to use PHP's built-in readfile() function:

<?php
$file = 'file.txt';

if (file_exists($file)) {
    readfile($file);
} else {
    echo 'File not found.';
}
?>

Force Browser Download with header()

If you want the browser to download the file instead of opening it, you can use the header() function to set HTTP headers:

<?php
$file = 'file.txt';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Length: ' . filesize($file));
    readfile($file);
} else {
    echo 'File not found.';
}
?>

Download Remote Files with cURL

When you need to download remote files or perform more complex operations, you can use the cURL library:

<?php
$url = 'https://example.com/file.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);

file_put_contents('file.txt', $data);
?>

These are the common methods for downloading files in PHP. Whether it's downloading a local file or fetching a remote file, these examples provide a straightforward guide for implementation.