Search code examples
phpfile-get-contents

Download file with PHP and file_get_contents


I would like to download files from a repository, I have the code below, the file is found, but nothing happens...

I have no error.

I used test values for the moment, but I will use GET later.

The target is to donwload the file directly :

$dossier = "../private/cartes_identites/test/";
$filename = "test.png";

$file = $dossier.$filename;

//First, see if the file exists
if (!is_file($file)) { die("<b>404 File not found!</b>"); }
else echo "file exists";

$ext = strrchr( $filename, "." );

switch( $ext ) {
    case ".zip": $type = "application/zip"; break;
    case ".txt": $type = "text/plain"; break;
    case ".pdf": $type = "application/pdf"; break;
    case('gif') : $type = "image/gif";break;
      case('pnggif') : $type = "image/png";break;
         case('jpg') : $type = "image/jpeg";break;


    default: $type = "application/octet-stream"; break;


}

echo $ext;

// Constitution de l'header suivant le type
header("Content-Description: File Transfer");
header("Content-Type: $type\n");
header("Content-Transfer-Encoding: binary");
header("Content-disposition: attachment; filename=$filename");
header("Content-Length: ".filesize( $dossier.$filename ) );


// Lecture et Affichage
file_get_contents( $dossier.$filename );
?>

this is the repository (test)


Solution

  • Currently you're just reading the file's content through file_get_contents, but you're never delivering the content to the client.

    Either echo the file's content to the user like this

    // ...
    header("Content-Length: ".filesize( $dossier.$filename ) );
    
    
    // Lecture et Affichage
    echo file_get_contents( $dossier.$filename );
    ?>
    

    or you can also use the readfile function instead of the file_get_contents like this:

    // ...
    header("Content-Length: ".filesize( $dossier.$filename ) );
    
    
    // Lecture et Affichage
    readfile( $dossier.$filename );
    ?>
    

    Also, you should get rid of the echo $ext; and only echo the file content, otherwise it might look like the file's corrupt.