Fenelon
Fenelon

Reputation: 113

Downloading file with PHP. How to get FILENAME?

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!

Upvotes: 2

Views: 2487

Answers (3)

Piskvor left the building
Piskvor left the building

Reputation: 92762

@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).

Upvotes: 0

Anthony
Anthony

Reputation: 37065

If you are using curl, the response header should return the actual filename. The header for file downloads looks like:

'Content-Disposition: attachment; filename="downloaded.pdf"'

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798716

The Content-Disposition header in the HTTP response, if it exists, will contain the filename the other server wants the file to have.

Upvotes: 8

Related Questions