Para descargar un fichero en PHP, debes indicar al navegador que debe descargar el fichero en el equipo del usuario en lugar de visualizarlo. En este artÃculo te mostraré cómo descargar un archivo de un directorio del servidor en PHP. En este tutorial también veremos cómo implementar un enlace de descarga que descargue un fichero de un directorio. El siguiente script de ejemplo puede ser utilizado para descargar cualquier tipo de fichero como un archivo de texto, documento, pdf, zip, etc.
Descargar un fichero en PHP
$fileName = basename('fichero.txt'); $filePath = 'files/'.$fileName; if(!empty($fileName) && file_exists($filePath)){ // Define headers header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=$fileName"); header("Content-Type: application/zip"); header("Content-Transfer-Encoding: binary"); // Read the file readfile($filePath); exit; }else{ echo 'The file does not exist.'; }
Descargar un fichero mediante un enlace
Hay veces que tenemos que proporcionarle un enlace al usuario para que pueda descargar un fichero del servidor. Puedes utilizar el siguiente código para mostrar un enlace HTML que descargue un fichero del servidor utilizando PHP.
Código HTML
<a href="download.php?file=fichero.png">Descargar fichero</a>
Código PHP (download.php)
<?php if(!empty($_GET['file'])){ $fileName = basename($_GET['file']); $filePath = 'files/'.$fileName; if(!empty($fileName) && file_exists($filePath)){ // Define headers header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=$fileName"); header("Content-Type: application/zip"); header("Content-Transfer-Encoding: binary"); // Read the file readfile($filePath); exit; }else{ echo 'The file does not exist.'; } }