Skip to main content
October 24, 2010
Answered

Forcing a file download vs opening a file when clicking a link...what's the best way to do this?

  • October 24, 2010
  • 1 reply
  • 321 views

Hello all,

What is the best way to ensure that when a user clicks a download link on a web page that the file actually downloads as opposed to the file opening in whatever program can read it? For my case this encompasses two file types, video files (.wmv predominantly) and .pdf files. I want my users to browse the list I provide for them, then they select a link, click and the file downloads, NOT have them play/open.

I began researching this last night, and the best I could come up with was the suggestion to add "&action=3Dsave" to the file name as a query string. So, me being curious, I tried with no success to find out if this is A) the right way to do it or B) if that query string is proper code for today's standards.

I looked on the w3c.org website not knowing if this was something that was within their realm, but their website has been redesigned and is now so cinfusing to navigate that one has to become a software engineer to figure it out.

Any help on this would be most appreciated. Thanks!

Sincerely,

wordman

This topic has been closed for replies.
Correct answer

Create a file with the same name as the video/pdf file but with the .php extension. Insert the following code at the very beginning (NO space before this in the file):

<?php

header('Content-disposition: attachment; filename=yourfilename.xyz');

header('Content-type: abc');

readfile('sourcefilename.xyz');

?>

substitute the file name for 'yourfilename' above. sourcefilename can be the same. This just gives you the option to change names.

You can find a list of mime types here: http://en.wikipedia.org/wiki/Mime_type

If you know php, If you have a lot of files, it probably would be easier to have all links go to a single page with the filename and mime type as parameters.You would then use simple substitution to do the rest.

1 reply

Correct answer
October 24, 2010

Create a file with the same name as the video/pdf file but with the .php extension. Insert the following code at the very beginning (NO space before this in the file):

<?php

header('Content-disposition: attachment; filename=yourfilename.xyz');

header('Content-type: abc');

readfile('sourcefilename.xyz');

?>

substitute the file name for 'yourfilename' above. sourcefilename can be the same. This just gives you the option to change names.

You can find a list of mime types here: http://en.wikipedia.org/wiki/Mime_type

If you know php, If you have a lot of files, it probably would be easier to have all links go to a single page with the filename and mime type as parameters.You would then use simple substitution to do the rest.