Learn how to download a file from a URL that returns a redirection instead of the file directly.

It's a common practice to serve files through PHP instead of serving them directly with PHP. Usually, as they are served after solving some captcha or something like that, you wont have a direct file download with the proper headers, but some random url that redirects to the file with the download headers. When you are trying to automatize stuff, this kind of behaviour is really a trouble. Personally, i decided to download the files with cURL, which makes pretty easy to download a file by simply following the redirection, for example:

curl -L -o "./download.zip"  "https://somewebsite.com/download-file.php"

This can be achieved simply using the -L parameter or the so called location. If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option will make curl redo the request on the new place:

curl -L -o "${filename}"  "${uri}"

Happy coding !


Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Become a more social person

Sponsors