0

I have a list of files, different types, when you click on for example a pdf it will show the pdf through a viewer.

I try to add a condition when it's not a pdf to download it directly. But i can't figure it out.

It's on a local file but how do i get to download that local file to my computer ? It downloads the viewer.php instead of the file in question and in the viewer.php there is some sort of ascii written in it.

VIEWER.PHP

// Si la variable $_GET['strPDF'] est définie ->
if ( isset($_GET['strPDF']) ) {
    // 'Décryption' de la variable ->
    $strPDF = hex2bin($_GET['strPDF']);
    // Connexion au serveur FTP et récupération du fichier demandé ->
    $streamFTP = ftp_connect($strFTP_Hote, $intFTP_Port, $intFTP_tOut);
    if ( ftp_login($streamFTP, $strUser, $strPass) ) {

        $tmpHandle = tmpfile(); 
        ftp_fget($streamFTP, $tmpHandle, $strPDF, FTP_BINARY);
        rewind($tmpHandle); 

        $contentType = mime_content_type($tmpHandle);

        $re = '/(\/pdf)/';
        preg_match($re, $contentType, $matches);
        if(count($matches) > 1){
            header('Content-type: ' . $contentType);
            echo stream_get_contents($tmpHandle);
        }
        else{
            header('Content-Description: File Transfer');
            header('Content-Type: application/force-download');
            // // header("Content-Disposition: attachment; filename=\"" . basename() . "\";");
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            // // header('Content-Length: ' . filesize());


            // it downloads viewer.php with some sort of ascii in it. 
            echo stream_get_contents($tmpHandle);
            exit;
        }

        fclose($tmpHandle);
    }
}
Bidoubiwa
  • 910
  • 2
  • 12
  • 25
  • 1
    Here is stackoverflow similar question with many of answers. http://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php – Prakash Saini Nov 23 '16 at 03:39
  • Hey yes i looked but my problem lies in the header ? Because i dont know what i have wrong here – Bidoubiwa Nov 23 '16 at 04:41
  • Yes your problem is headers. And the answers in the question linked by @PrakashSaini shows the correct headers. – Martin Prikryl Nov 23 '16 at 07:09

1 Answers1

1

Use the Content-Disposition header.

header("Content-Disposition: attachment; filename=\"my.pdf\";");

You will probably want to extract a real name from the $strPDF:

header("Content-Disposition: attachment; filename=\"" . basename($strPDF) . "\";");

You should also add the Content-Length header.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992