"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Force File Download in PHP?

How to Force File Download in PHP?

Published on 2024-11-04
Browse:367

How to Force File Download in PHP?

Force File Download in PHP

To provide a download link for a file in PHP, you can use the following steps:

  1. Retrieve the File Information:

    $filePath = '/path/to/file/on/disk.jpg';
    
    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);
    } else {
        die('The provided file path is not valid.');
    }
  2. Output Headers:

    header("Cache-Control: private");
    header("Content-Type: application/stream");
    header("Content-Length: ".$fileSize);
    header("Content-Disposition: attachment; filename=".$fileName);
  3. Output the File:

    readfile ($filePath);                   
    exit();

Note: Be cautious if implementing this in a function to allow downloads of arbitrary files, as you need to prevent directory traversal and restrict downloads to a defined area.

Release Statement This article is reprinted at: 1729425315 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3