php forces file download instead of custom function sharing open in browser

  • 2021-06-28 08:57:03
  • OfStack

Sometimes we want to download pictures, text documents, web pages, mp3, pdf, etc. when we click on the corresponding link, instead of displaying it on the web page, then we need to force the header header information.The following is a code implementation of the php function that does not generate garbage and can be referenced by other programming languages.


/**
 * Downloader
 *
 * @param $archivo
 *  path al archivo
 * @param $downloadfilename
 *  (null|string) el nombre que queres usar para el archivo que se va a descargar.
 *  (si no lo especificas usa el nombre actual del archivo)
 *
 * @return file stream
 */
function download_file($archivo, $downloadfilename = null) {
    if (file_exists($archivo)) {
        $downloadfilename = $downloadfilename !== null ? $downloadfilename : basename($archivo);
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . $downloadfilename);
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($archivo));
        ob_clean();
        flush();
        readfile($archivo);
        exit;
    }
}


Related articles: