Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Download from PHP server to client

Status
Not open for further replies.

ojf

Instructor
Sep 27, 2000
49
NO
What is the best method to use to download a file from PHP server to client?

ojf
 
I need a piece of code which will start the downloading process when a user either clicks on a button or a link.

The actual files will be exe, doc, zip and so on.

ojf
 
If you want to click on a link and have the browser download a file, just provide a link directly to the file and let the web server and browser deal with it outside of PHP.

If you want PHP to have control over the process (you want to verify a login or something) then something like this:

Code:
<?php
header(&quot;Content-Disposition: attachment; filename=<yourfilenamehere>&quot;);
header(&quot;Content-Transfer-Encoding: binary&quot;);
header(&quot;Content-Type: application/octet-stream&quot;);
readfile (&quot;<yourfilenamehere>&quot;);
?>

will instruct PHP to shoot the file out to the browser. The &quot;Content-Disposition&quot; header will cause the browser to pop up a &quot;Save file&quot; dialog, with the filename (which can be different from the name of the script) already populated.

Two gotchas:

You should match the &quot;Content-Type&quot; header to the type of file you're sending. For example, if you're sending a PDF, the content type should read &quot;application/pdf&quot;, though &quot;application/octet-stream&quot; will likely work, too.

If your browser knows how to handle the file internally, it may not open the &quot;Save file&quot; dialog at all. For example, if you're sending a text file with a content-type of &quot;text/plain&quot; and a file extension of &quot;.txt&quot;, your browser may only display the file. Want the best answers? Ask the best questions: TANSTAAFL!
 
And I use this code i.e. for CSV file:
$file_type = &quot;csv&quot;;
$file_ending = &quot;csv&quot;;
header(&quot;Content-Type: application/$file_type&quot;);
header(&quot;Content-Disposition: attachment; filename=invmil.$file_ending&quot;);
header(&quot;Pragma: no-cache&quot;);
header(&quot;Expires: 0&quot;);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top