PHP for sending a file to the client for download

Code Solution for Sending a File to the Client for Download


// Get the file path from the request parameter
$filePath = $_GET['file_path'];

// Check if the file exists
if (!file_exists($filePath)) {
    header("HTTP/1.0 404 Not Found");

// Get the file size
$fileSize = filesize($filePath);

// Set the appropriate headers
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . basename($filePath) . "\"");
header("Content-Length: $fileSize");

// Output the file content

How it works

  1. The code first checks if the file exists. The file_exists() function is used for this purpose. If the file does not exist, it sets the HTTP status code to 404 and exits the script.
  2. Next, it gets the file size using the filesize() function. This is necessary for setting the Content-Length header.
  3. It then sets the appropriate headers for the file download:
    • Content-Type: application/octet-stream: This sets the content type to octet-stream, which indicates that the content is a binary file.
    • Content-Disposition: attachment; filename="filename.txt": This sets the content disposition to attachment and specifies the filename of the downloaded file.
    • Content-Length: $fileSize: This sets the content length to the size of the file in bytes.
  4. Finally, it outputs the file content using the readfile() function.

How to implement it effectively

  1. Make sure that the file path is passed as a parameter to the script. You can do this using the $_GET or $_POST global variables.
  2. Check for file existence before attempting to download it.
  3. Set the appropriate headers for the file download. This is important to ensure that the browser correctly handles the downloaded file.
  4. Use the readfile() function to output the file content. This is the most efficient way to download a file in PHP.