tags:

views:

303

answers:

4

Hi,

i want to serve an existing file to the browser in php. i've seen examples about imagejpeg but that function seems to save a file to disk and you have to create a right sized image object first... (or i just don't understand it :))

in asp.net i do it by reading the file in a byte array and the call context.Response.BinaryWrite(bytearray), so i'm looking for something similar in php.

Michel

+1  A: 

This should get you started: http://de.php.net/manual/en/function.readfile.php

Edit: If your web server supports it, using

header('X-Sendfile: ' . $filename);

where file name contains a local path like

/var/www/www.example.org/downloads/example.zip

is faster than readfile().

(usual security considerations for using header() apply)

KiNgMaR
+2  A: 

There is fpassthru() that should do exactly what you need. See the manual entry for an example.

See here for all of PHP's filesystem functions.

If it's a binary file you want to offer for download, you probably also want to send the right headers so the "Save as.." dialog pops up. See the 1st answer to this question for a good example on what headers to send.

Pekka
thanks, exactly what i needed.
Michel
+1  A: 

For both my website and websites I create for clients I use a PHP script that I found a long time ago.

It can be found here: http://www.zubrag.com/scripts/download.php

I use a slightly modified version of it to allow me to obfuscate the file system structure (which it does by default) in addition to not allowing hot linking (default) and I added some additional tracking features, such as referrer, IP (default), and other such data that I might need should something come up.

Hope this helps.

David
Thanks for the script. If i want to expand my first script i'll definately will use it.
Michel
+1  A: 

I use readfile() ( http://www.php.net/readfile )...

But you have to make sure you set the right "Content-Type" with header() so the browser knows what to do with the file.

You can also force the browser to download the file instead of trying to use a plug-in to display it (like for PDFs), I always found this to look a bit "hacky", but it is explained at the above link.

berty