Force Download Files in PHP

One of the most common problems that we find is to force the download of a certain file from the client’s browser, thus preventing it from opening.
For this we can use the following function in PHP.

function force_download($file)
{
    if ((isset($file))&&(file_exists($file))) {
       header("Content-length: ".filesize($file));
       header('Content-Type: application/octet-stream');
       header('Content-Disposition: attachment; filename="' . $file . '"');
       readfile("$file");
    } else {
       echo "No selected file";
    }
}

 

Rúa Pilar Miró n 6 Santiago de Compostela

Jersey St , Manchester, Greater Manchester M4 6JG, GB

T. 609 538 171 - 634 59 34 43

info@teslatechnologies.com