Skip to content

Instantly share code, notes, and snippets.

@cdmz
Created July 22, 2015 19:09
Show Gist options
  • Save cdmz/6c919fc8801b5eab5534 to your computer and use it in GitHub Desktop.
Save cdmz/6c919fc8801b5eab5534 to your computer and use it in GitHub Desktop.
Download files with php
<?php
//Referencia do arquivo
$arquivo = $_GET["arquivo"];
//get file ...
$path = /*path file here*/
if(isset($path) && file_exists($path)){
// verifica se a extensão do arquivo é permitida para baixar
switch(strtolower(substr(strrchr(basename($path),"."),1))){
// verifica a extensão do arquivo para pegar o tipo
case "pdf": $tipo="application/pdf"; break;
case "exe": $tipo="application/octet-stream"; break;
case "zip": $tipo="application/zip"; break;
case "doc": $tipo="application/msword"; break;
case "xls": $tipo="application/vnd.ms-excel"; break;
case "ppt": $tipo="application/vnd.ms-powerpoint"; break;
case "gif": $tipo="image/gif"; break;
case "png": $tipo="image/png"; break;
case "jpg": $tipo="image/jpg"; break;
case "mp3": $tipo="audio/mpeg"; break;
case "php": die(); break;
case "htm": die(); break;
case "html": die(); break;
}
header("Content-Type: ".$tipo); // informa o tipo do arquivo ao navegador
header("Content-Length: ".filesize($path)); // informa o tamanho do arquivo ao navegador
header("Content-Disposition: attachment; filename=".basename($path)); // informa ao navegador que é tipo anexo e faz abrir a janela de download, tambem informa o nome do arquivo
readfile($path); // lê o arquivo
exit; // aborta pós-ações
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment