High CPU usage when streaming a file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
maxmil
Forum Newbie
Posts: 3
Joined: Tue Oct 09, 2007 5:44 am

High CPU usage when streaming a file

Post 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
miro_igov
Forum Contributor
Posts: 485
Joined: Fri Mar 31, 2006 5:06 am
Location: Bulgaria

Post by miro_igov »

Did you tried readfile() ?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

Try to call ob_end_clean() just before your second code snippet. What is your PHP version?
There are 10 types of people in this world, those who understand binary and those who don't
maxmil
Forum Newbie
Posts: 3
Joined: Tue Oct 09, 2007 5:44 am

Post by maxmil »

PHP Version: 5.2.0
Apache: 2.0.59

I have tried both ob_end_clean() and readFile() but the problem remains.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post 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?
There are 10 types of people in this world, those who understand binary and those who don't
maxmil
Forum Newbie
Posts: 3
Joined: Tue Oct 09, 2007 5:44 am

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Or you could call set_time_limit().
Post Reply