0

I am trying to download files from server and it works fine for pdf files, I am wondering is there a way to download any type of files such as doc, zip,.. etc.

My code:

<?php
$doc = $sqlite->readDoc($documentId);
    if ($doc != null) {
        header("Content-Type:" . $doc['mime_type']);
        header('Content-disposition: attachment; filename="something"');
        print $doc['doc'];

    } else {
        echo 'Error occured while downloading the file';
    }
?>
SMH
  • 1,276
  • 3
  • 20
  • 40
  • Your comments to @ZaidBinKhalid seem to suggest a different problem than what is formulated in your question. Please clarify your question, by editing it: does the downloading not work for other files than pdf files (meaning you are not receiving anything / no download dialog appears / etc.), or are you simply unable to determine a proper filename extension for the download? – Decent Dabbler Nov 27 '17 at 01:06

2 Answers2

1

You'll want to identify the file - maybe using this function:

http://php.net/manual/en/function.mime-content-type.php

and then you can create a switch to indicate the content-type and appropriate disposition. There's a decent example here: PHP - send file to user

1

A simple function that can be used to download any file formate form path.

function DownloadFile($strFilePath)
{
        $strContents = file_get_contents(realpath($strFilePath));
        if (strpos($strFilePath,"\\") > -1 )
            $strFileName = substr($strFilePath,strrpos($strFilePath,"\\")+1);
        else
            $strFileName = substr($strFilePath,strrpos($strFilePath,"/")+1);
        header('Content-Type: application/octet-stream');
        header("Content-Disposition: attachment; filename=\"${strFileName}\"");
        echo $strContents;
}

Usage Example

$file = $_GET['file_id'];
$path = "../uploads/".$file; // change the path to fit your websites document structure
DownloadFile($path);
Zaid Bin Khalid
  • 748
  • 8
  • 25
  • The problem is in the extension of the file, I want to add the extension based on the type of file pdf, doc ..etc – SMH Nov 27 '17 at 00:35
  • Did you try this function? You no need to worry about extension now just pass the file name with the absolute path like. `upload/somthing.pdf` or `upload/somthing.doc` or `upload/somthing.jpg` etc. – Zaid Bin Khalid Nov 27 '17 at 00:38
  • I dont have a path as I read the file from the DB, I edited my question – SMH Nov 27 '17 at 00:42
  • If the file does not physically exist on the server then how could you download a file? When you upload a file and save its name into `DB` than where you save your file? – Zaid Bin Khalid Nov 27 '17 at 00:46
  • they file is already in the DB and I am trying to download it – SMH Nov 27 '17 at 01:01