How to download file in PHP?

The readfile() function is used to download the file in PHP.

int readfile ( string $filename )

To download a file in PHP, you typically follow these steps:

  1. Specify the file to be downloaded: You need to know the path or URL of the file you want to download.
  2. Set appropriate headers: Use PHP’s header function to set the appropriate headers for file download. This includes the content type, content-disposition, and possibly content-length headers.
  3. Output the file contents: Depending on the file location (local or remote), you’ll need to either read the file contents and output them directly or fetch the file contents from a remote location and output them.

Here’s a basic example:

php
<?php
// File to be downloaded
$file = 'path/to/your/file';

// Check if the file exists
if (file_exists($file)) {
// Set headers
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
// Output the file
readfile($file);
exit;
} else {
// File not found
die('File not found');
}
?>

In this code:

  • $file variable holds the path to the file to be downloaded.
  • header functions set the appropriate headers for file download.
  • readfile function outputs the file contents.

Ensure to replace 'path/to/your/file' with the actual path to the file you want to download. Also, keep in mind that this example assumes the file exists on the server. If the file is located on a remote server, you might need to use different functions to fetch its contents, such as file_get_contents.