Ultrashock Forums > Development > Server Side
PHP - Steaming Files + Limiting Length

You are currently viewing our website as a guest which gives you limited access to forums, files and other resources.

Click here to join now for free, and start interacting with our members, download files and much more!

Click here if you are looking for our Flash files and other professional assets.
 
Post Reply | View first unread | Rate Thread Search this Thread | Thread Tools | Display Modes

#1
Bookmark and Share!
PHP - Steaming Files + Limiting Length
Old 2008-11-05

Hi guys,

I am currently using the following PHP function to stream files:

Code:
/**
 * @return void
 */
protected final function stream( $filePath, $offset, $maxLength=null )
{
	if( $maxLength === null )
	{
		$maxLength = filesize( $filePath );
	}

	$chunk = 32;
	$total = 0;

	$handle = fopen( $filePath, "rb" );

	if( $handle )
	{
		fseek( $handle, $offset );
		
		while( feof( $handle ) == false )
		{
			echo( fread( $handle, $chunk ) );

			$total += $chunk;

			if( $total >= $maxLength )
			{
				break;
			}
		}

		fclose( $handle );
	}
}
As you can see I have a $chunk variable defined that limits the size of each "packet" pulled from the file, I'm doing this to cap the length of data that can be read. I have a couple of questions regarding this technique:

How much of an impact on server (file system) resources would this have? For example, would it be a big no-no to set the $chunk value to 1.

Would it be bad to cut the stream if it was in the middle of a MP3 or FLV tag?

I have run a little test streaming a standard FLV file from a server, and I am able to seek to any point in the file at any time, but I would like some pointers/tips from PHPers who have had experience with this kind of thing (I don't want to end up killing servers or SWF files etc).

Thanks.

PS: Who needs FMS when you have PHP.
www.si-robertson.com
postbit arrow 1 comment | 378 views postbit arrow Reply: with Quote   
Registered User
Nutrox is offline
seperator
Posts: 11,566
2004-04-25
Age: 31
Nutrox lives in United Kingdom
13
Nutrox's Avatar
seperator

Ultrashock Member Comments:
Nutrox's Avatar Nutrox Nutrox is offline Nutrox lives in United Kingdom 13 Creative Assets 2008-11-06 #2 Old  
No problem with this one guys, I think I have nailed it. I have increased the chunk size to 4096 bytes (adjustable by the client), added a flush() after the echo() to make sure the bytes get pushed to the client as a stream, setup a shutdown handler to catch aborted connections, and also made sure the correct headers are sent when a client tries to continue a download/stream after disconnecting. It all seems to be working as expected.
Reply With Quote  
Thread Tools
Display Modes Rate This Thread
Rate This Thread: