Download file with PHP. How do I get FILENAME?

advertisements

I need to download files from remote server with my PHP script. The problem is that the links I recieve look like "example.com?download=12345". So I want to save the file with correct extension and (at best) preserve it's original filename. How do I do this? Thank you all!


@EricLaw (of the IE Team) has posted a detailed analysis of this on the IEBlog last November. While his post is focused on IE, the basics hold for most browsers:

  • use a Content-Disposition header (cleanest, standard-compliant, allows you to specify the filename; can be combined with either of the following)
  • don't use a query-string (not always practical - but possible with URL rewriting)
  • "Add a bogus querystring parameter at the end with the desired extension" (a bit of a hack, but works)

However, the source server is not obliged to do any of this; the most likely option would be the Content-Disposition header. If that is not present, you are back to square 1 (although you could guesstimate the file type from its content).