2

In my project, I need to download a file, and I need to use PHP.
All the results from Google were eventually not very helpful.

After combining code from 2 results, I ended up attempting:

function downloadFile($url, $filename) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $data = curl_exec($ch);
    curl_close($ch);

    header('Content-Description: File Transfer');
    header('Content-Type: audio/*');
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($data));
    readfile($data);
}

The result is an audio file, weighs 10KB (should be 3.58MB).
This code isn't the same as the code in the question that was suggested as a duplicate - here there's a section of curl functions and headers, while the question's answer only has a bunch of headers.

When opened the file with VLC - the following error appears:

Also, I tried using:

file_put_contents($filename, file_get_contents($url));

This one results in downloading the file to the path in which the PHP file is located at - which is not what I want - I need the file to be downloaded to the Downloads folder.

So now I'm basically lost.
What's the appropriate way to download files?

Thanks!

avi12
  • 2,000
  • 5
  • 24
  • 41

1 Answers1

2

I successfully did it, thanks to Google and a lot of experiments.
The final code:

function downloadFile($url, $filename) {
    $cURL = curl_init($url);
    curl_setopt_array($cURL, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FILE           => fopen("Downloads/$filename", "w+"),
        CURLOPT_USERAGENT      => $_SERVER["HTTP_USER_AGENT"]
    ]);

    $data = curl_exec($cURL);
    curl_close($cURL);
    header("Content-Disposition: attachment; filename=\"$filename\"");
    echo $data;
}
avi12
  • 2,000
  • 5
  • 24
  • 41