Home > Mobile >  PHP rest api how to return a file or download
PHP rest api how to return a file or download

Time:11-25

I have an rest api and the endpoint is getfilestart.php. What it does is that it searches for the filename in the database using PDO. How can I get the file and return it as a file or automatically download it using postman or in the browser? I tried several methods but I cannot get the file. The directory is in ../files/

Here is the function for download

    public function downloadFile($param){
        $base_url = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];
     
        $q = "SELECT * FROM data_file WHERE module_id = ". $param;
        $stmt = $this->conn->prepare($q);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $filename = $row['file_name'];
        $request_url = $base_url .'/mtc_project_server/files/'.$filename;
    }

If i dump the request_url its http://localhost/mtc_project_server/files/mir4.PNG which is the actual file. How can i download it using rest? I tried doing cURL and file_get_contents and still not working. Thanks in advance

CodePudding user response:

From your download file URL $request_url.
This is force download source code for server side.

// https://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php

header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($request_url) . ".jpg\""); 
readfile($request_url);
exit();// end process to prevent any problems.

This is source code for download working on client side.

$url = 'https://my-domain.tld/rest-api/path.php';// change this to your REST API URL.

// https://stackoverflow.com/questions/6409462/downloading-a-large-file-using-curl

$fileext = pathinfo($url, PATHINFO_EXTENSION);
echo $fileext;
set_time_limit(0);
// For save data to temp file.
$fp = fopen (__DIR__ . '/localfile.tmp', 'w ');

//Here is the file we are downloading, replace spaces with  
$ch = curl_init(str_replace(" "," ",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);

// get curl response
$response = curl_exec($ch); 

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

fwrite($fp, $body);

curl_close($ch);
fclose($fp);

// rename temp file.
preg_match('/filename=[\'"]?([\w\d\.\-_] )[\'"]?/i', $header, $matches);
var_dump($matches);
if (isset($matches[1]) && !is_file(__DIR__ . '/' . $matches[1])) {
    // if target rename file is not exists.
    rename(__DIR__ . '/localfile.tmp', __DIR__ . '/' . $matches[1]);
} else {
    // for debug
    echo 'something wrong!<br>';
    var_dump($matches);
    echo '<br>';
    echo 'File was downloaded into ' . __DIR__ . '/localfile.tmp';
    exit();
}
  • Related