Moon
Moon

Reputation: 22605

performance of passthru("cat file")

I'm using passthru("cat filepath") in my download script. My concern is that it might use a lot of server resource.

What is the difference between directly link a file in a public directory and download a file using passthru("cat filepath") in php?

Upvotes: 1

Views: 3659

Answers (3)

Andrew Moore
Andrew Moore

Reputation: 95444

Don't use passthru() for that, you're opening yourself to CLI Injection and performance is terrible. readfile() exists just for that.

readfile($filepath);

There is a small overhead when passing through PHP compared to a direct link but we are usually talking of milliseconds. However, the browser will not be able to request a 206 Partial when using readfile() unless you code support for it or use something like PEAR::HTTP_Download.

EDIT: Seems you are using passthru() because apparently readfile() doesn't handle >2GB files properly (I never had that problem with readfile(), in fact I just tested it with a 7.2 GB file and it worked fine). In which case, at least escape your parameters.

function readfile_ext($filepath) {
  if(!file_exists($filepath))
    return false;

   passthru('cat ' . escapeshellarg($filepath));
   return true;
}

Upvotes: 3

Charles
Charles

Reputation: 51421

What is the difference between directly link a file in a public directory and download a file using passthru("cat filepath") in php?

The difference is that linking directly to a file does not invoke PHP, while running a PHP script which in turn runs cat causes, well, both PHP and cat to be invoked. This will take up a moderate amount of extra memory, but won't cause server load under most circumstances.

I was using readfile(), but this function can't be used for files larger than 2gb

You might want to find a better solution than passing all of the file contents through PHP, in that case. Look into X-Sendfile support in your web server software of choice.

Upvotes: 4

deceze
deceze

Reputation: 522597

Instead of passthru('cat filepath'), use the PHP native readfile('filepath'), which has better performance.

Both methods will be slower than simply directly linking to the file though, since PHP has a certain overhead.

Upvotes: 2

Related Questions