tags:

views:

63

answers:

3

I wrote a toPdf class in PHP that has the ability to stream it to the browser. If the file is not marked as savable, I need to perform clean up after I stream it. Since that is not possible, I'm wondering if there is a way to read the file into a variable, perform my clean up, send the headers, then start the file steam?

Thanks!

+1  A: 

You could do something like

!headers_sent() or die('something has already been sent to the client');

header('Content-type: application/pdf');
readfile($file);
unlink($file);

(and also take a look at http://docs.php.net/function.ignore_user_abort)

VolkerK
A: 

Try output buffering (http://us.php.net/manual/en/book.outcontrol.php).

The only problem I could see happening here is that if your files are extremely large you are basically creating a full copy of the file in memory (the buffer), but ob is intended to capture all output from the script (except headers), and hopefully will do the trick.

eCaroth
A: 

When you chain unix commands like sort data.txt | less effectively the stdout of one command "becomes" the stdin of another command. You can do kinda same with php when calling another process. But in your case you want the data from stdout of one process and send it to php's stdout (sending it to the client).
The simplest way is to use passthru()

header('Content-type: application/pdf');
passthru('yourcommand -o -');

But since you have to set the application/pdf header before the commands sends any output the error handling might be tricky. The client expects a PDF document and if you send something else, e.g. a plain text error message, the result will be ...confusing.
Still, you can fetch the data from your command's stdout but without php automagically glueing the stdout to php's stdout. see popen() and/or proc_open(). You'll get a handle you can read from (almost like a file handle) and get the output the application made to stdout (with proc_open you also get the stderr stream) without any physical file laying around.

VolkerK