views:

169

answers:

2

I'm writing a tool that allows someone to connect to a web page and generate files for download on the fly.

To write these files, I can use PHP functions like fopen or fwrite, or I could create a script that can be called as a system call to generate the output such as:

php downloadGen.php > filetocreate.xml

The fwrite version of the solution uses more memory and is also slower than the piped version. Does anyone see any problems with executing the download generation as a system call? Would there be a cap on how many calls I could be running simultaneously?

Anyway, I'm hoping someone has experience with something similar and can offer some advice...

A: 

The easiest and most efficient way (available since PHP 5.0) is to simply use file_put_contents() to insert the contents into the file. You specify the filename as the first parameter, and the string (either binary or simple text - it's a binary-safe function) of data to input into the file.

It will then generate the file at the path that you specify.

And to answer your second point, unless you have:

  1. A HUGE number of users,
  2. You are writing HUGE files constantly, or
  3. Your server is crap

Then you'll be fine.

BraedenP
the problem with using file_put_contents is that I would have to store up the entire output in a variable prior out dumping it to the file.
Dave Johnshon
+1  A: 

The fwrite version of the solution uses more memory and is also slower than the piped version

Are you sure? I'll bet dollars to donuts it's the opposite (but in a negligible sort of way), and you're just measuring wrong.

Memory -

Building the file in-process via fopen/fwrite should consume less memory than creating a separate process on the server. Perhaps you think it's the other way around because you're measuring how much memory your script is consuming. But that php downloadGen.xml system call is starting up another process. The PHP code there will use as much memory as it would if you did it in your webserver-bound process, plus all the overhead of cli php process. So the difference should be negligible.

"Speed" -

The same applies to speed. Starting up the PHP interpreter consumes processor cycles. If you're doing this all synchronously, putting your generation/output code in the main script should be faster. But only barely.

timdev