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!