Home > Article > Backend Development > PHP forces file downloading instead of sharing custom functions opened in the browser_PHP Tutorial
Sometimes we want content such as pictures, text documents, web pages, mp3, pdf, etc. to be downloaded directly when the corresponding link is clicked instead of displayed on the web page, then we need to forcefully set the header information. The following is a PHP function implementation code that will not produce garbled characters. Other programming languages can also refer to it for writing and implementation.
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;
}
}