Implementare il download dei file in PHP

Implementare il download dei file in PHP

In PHP è relativamente semplice implementare una soluzione per il download dei file.

La soluzione è la seguente:


function download($path) {
    $filename = null;
    if (isset($_GET['file']) && basename($_GET['file']) == $_GET['file']) {
        $filename = $_GET['file'];
    }
    if(!is_null($filename)) {
        $full_path = $_SERVER['DOCUMENT_ROOT'] . $path . $filename;
        if (file_exists($full_path) && is_readable($full_path)) {
            header('Content-Type: application/octet-stream');
            header('Content-Length: '. filesize($full_path));
            header('Content-Disposition: attachment; filename=' . $filename);
            header('Content-Transfer-Encoding: binary');
            readfile($full_path);
        } else {
            exit();
        }
    } else {
        exit();
    }    
}

Esempio d'uso:


<?php
// download.php
download('/images/');

Torna su