Page 1 of 1

High CPU usage when streaming a file

Posted: Tue Oct 09, 2007 5:50 am
by maxmil
Hi,

I have a web application that allows users to download pdf files from the server. To control access to these files they are not in a directory that is visible from the web. When a user requests one of the files the code sets the necessary headers and writes the files bytes to the output. Using

Code: Select all

fpassthru($file);
flush();

The problem is that when this occurs there is a peak in the CPU usage of the server which can (momentarily) go as far up as 100%.

I have tried other methods of streaming the file such as

Code: Select all

while(!feof($file)) {
   print(fread($file, 1024*8));
   flush();
}

But the result is the same.

How can i control these peaks in the CPU usage? Any comments welcome.

max

Posted: Tue Oct 09, 2007 6:09 am
by miro_igov
Did you tried readfile() ?

Posted: Tue Oct 09, 2007 6:12 am
by VladSun
Try to call ob_end_clean() just before your second code snippet. What is your PHP version?

Posted: Tue Oct 09, 2007 6:51 am
by maxmil
PHP Version: 5.2.0
Apache: 2.0.59

I have tried both ob_end_clean() and readFile() but the problem remains.

Posted: Tue Oct 09, 2007 7:04 am
by VladSun
You may try to include usleep() in your loop. And another question (I have to ask it :) ) - when calling fopen() you are not passing an URL, are you?

Posted: Tue Oct 09, 2007 10:07 am
by maxmil
No its not a URL, its a local file. The file however can be as big as 100Mb!

usleep() works perfectly to control de CPU. The problem that it incurs is that the the scipt can now exceed the maximum execution time (by default 30 seconds). It could be possible to play with the sleep time, this value and the maximum file size to find a solution but i fear that it would not be a very stable one.

Maybe i'll just have to allow users a direct link to these files instead of passing them through the php script.

Thanks for your help.

max

Posted: Tue Oct 09, 2007 10:19 am
by feyd
Or you could call set_time_limit().