[PHP] Forzare download file
Ciao a tutti,
ho un problema con php. Vorrei far scaricare agli utenti un file attraverso php, ma il file (di dimensioni giuste) non viene aperto da nessun programma (errore nell'apertura del file). Ho provato con jpeg, png, gif, doc ma niente. L'unico che al momento funziona è txt.
Utilizzo questa funzione:
Codice PHP:
<?php
// Includo la connessione al database
require('config.php');
function download($path, $name = null)
{
//elenco dei mime types
$mime_types = array(
"bmp" => "image/bmp",
"exe" => "application/octet-stream",
"html" => "text/html",
"ico" => "image/x-icon",
"jpeg" => "image/jpeg",
"png" => "image/png",
"jpg" => "image/jpeg",
"mov" => "video/quicktime",
"mp3" => "audio/mpeg",
"mp4" => "video/mpeg",
"mpeg" => "video/mpeg",
"mpg" => "video/mpeg",
"txt" => "text/plain",
"wav" => "audio/x-wav",
"zip" => "application/zip"
);
//ricava l'estensione del file (senza il punto)
$ext = substr(strrchr($path,'.'),1);
//ricava il mime type dall'array
$mime_type = $mime_types[$ext];
//se non viene specificato un nome nel secondo parametro
if($name == null){
//ricava il nome del file
$name = substr($path, strrpos($path,'/'),strlen($path)-strrpos($path,'/'));
} else {
//altrimenti usa il nome specificato e concatena l'estensione
$name = $name.'.'.$ext;
}
if (headers_sent()) {
echo 'Errore : gli headers HTTP sono già stati inviati.';
exit;
}
$path = realpath($path);
//se il file non esiste
if ($path === false || !is_file($path) || !is_readable($path)) {
header('HTTP/1.0 204 No Content');
exit;
}
$size = filesize($path);//calcola dimensione del file
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Cache-Control: private');
header('Pragma: no-cache');
header("Content-Transfer-Encoding: binary");
header("Content-type: {mime_type}");
header("Content-length: {$size}");
header("Content-disposition: attachment; filename=\"{$name}\"");
readfile($path);
exit;
}?>
Sapreste aiutarmi? Grazie a tutti :crycry::crycry: