PHP: Forçar download de um arquivo

Olá! Segue abaixo um código exemplo de como forçar o download de arquivos com PHP.



<?php

$arquivo1 = 'teste.jpg';

if ($arquivo1) {
$extensao = strtolower(substr(strrchr($arquivo1, "."), 1));

switch ($extensao) {
case "pdf" :
$ctype = "application/pdf";
break;
case "exe" :
$ctype = "application/octet-stream";
break;
case "zip" :
$ctype = "application/zip";
break;
case "doc" :
$ctype = "application/msword";
break;
case "xls" :
$ctype = "application/vnd.ms-excel";
break;
case "ppt" :
$ctype = "application/vnd.ms-powerpoint";
break;
case "gif" :
$ctype = "image/gif";
break;
case "png" :
$ctype = "image/png";
break;
case "jpe" :
case "jpeg" :
case "jpg" :
$ctype = "image/jpg";
break;
default :
$ctype = "application/force-download";
}

if (!file_exists($arquivo1)) {
die("Arquivo não encontrado");
}

}

if ($arquivo1) {
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"" . basename($arquivo1) . "\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($arquivo1));
set_time_limit(0);
ob_clean();//Limpa a saida do buffer
flush();//da a descarga
readfile($arquivo1) or die('Download incompleto');
exit;
}
?>

Nenhum comentário:

Postar um comentário