How to download a file from a URL with redirection using Curl

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 !

This could interest you

Become a more social person