Trouble downloading a file in browser using CURL

Refresh

April 2019

Views

50 time

2

I have a problem I am trying to solve. The issue is downloading a file using CURL and offering a Save As prompt to the user in browser when this happens. I can successfully open the file but it opens directly in the browser as character data.

So far I have tried using the standard Content-Type and Content-Disposition headers with no luck actually producing the save dialogue prompt:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "ftp://server.com/recordings/4_23_2019/CD36FAFA9DFD4DE190B487C503D5A3D2 @ 2_04_28 PM.wav");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file); #output
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
$file = curl_exec($ch);
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="CD36FAFA9DFD4DE190B487C503D5A3D2 @ 2_04_28 PM.wav"');
    header('Content-Transfer-Encoding: binary');
    header('Content-length: ' . filesize($file));
    readfile($file);
    exit;
}
?>

I believe using these headers should offer a save prompt to the user, but instead I get a page with a bunch of random characters.

Errors Produced:

Warning: file_exists() expects parameter 1 to be resource, string given in /path/name

Warning: Cannot modify header information - headers already sent

P A

1 answers

0

$file is resource and $mypath is filepath

<?php
$mypath = "/var/www/mypath/myfile.ext";
$file = fopen ($mypath, 'w+') or die('Unable to write a file'); 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "ftp://server.com/recordings/4_23_2019/CD36FAFA9DFD4DE190B487C503D5A3D2 @ 2_04_28 PM.wav");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file); #output
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
$file = curl_exec($ch);
curl_close($ch);                               
fclose($file);

if (file_exists($mypath)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="CD36FAFA9DFD4DE190B487C503D5A3D2 @ 2_04_28 PM.wav"');
    header('Content-Transfer-Encoding: binary');
    header('Content-length: ' . filesize($mypath));
    readfile($mypath);
    exit;
}
?>