Monday, January 11, 2010

File Download using PHP Script

PHP File Download:

// First Parameter $file = “Filename”;

// Second Parameter $rate = “File transfer rate”;

function send_file($file, $rate = 0) {

// Check if the file exists

if (!is_file($file))

{

die(‘404 File Not Found’);

}

// Get the filename, extension, and size

$filename = basename($file);

$file_extension = strtolower(substr(strrchr($filename, ‘.’), 1));

$size = filesize($file);

// Set the mime type based on the extension

switch($file_extension)

{

case ‘exe’:

$ctype = ‘application/octet-stream’;

break;

case ‘zip’:

$ctype = ‘application/zip’;

break;

case ‘mp3′:

$ctype = ‘audio/mpeg’;

break;

case ‘mpg’:

$ctype = ‘video/mpeg’;

break;

case ‘avi’:

$ctype = ‘video/x-msvideo’;

break;

//  Block access to sensitive file types

case ‘php’:

case ‘inc’:

exit;

break;

default:

$ctype=’application/force-download’;

}

// Begin writing headers

header(‘Cache-Control: private’);

header(‘Content-Type: ‘ . $ctype);

header(‘Content-Disposition: attachment; filename=’ . $filename);

header(‘Content-Transfer-Encoding: binary’);

header(‘Accept-Ranges: bytes’);

// Open the file for reading

$fp = fopen($file, ‘rb’);

// Check if http_range was sent by client

if(isset($_SERVER['HTTP_RANGE']))

{

// If so, calculate the range to use

$seek_range = substr($_SERVER['HTTP_RANGE'], 6);

$range = explode(‘-’, $seek_range);

if($range[0] > 0){

$seek_start = intval($range[0]);

}

if($range[1] > 0){

$seek_end  =  intval($range[1]);

}

// Seek to the requested position in the file

fseek($fp, $seek_start);

// Set the range response headers

header(‘HTTP/1.1 206 Partial Content’);

header(‘Content-Length: ‘ . ($seek_end – $seek_start + 1));

header(sprintf(‘Content-Range: bytes %d-%d/%d’, $seek_start, $seek_end, $size));

}

else

{

// Set default response headers

header(‘Content-Length: ‘ . $size);

}

// Set up the size of each piece of data we send

$block_size = 1024;

if($rate > 0)

{

// Multiply by rate if specified

$block_size *= $rate;

}

// Prevent the script from timing out

set_time_limit(0);

// Start sending the file

while(!feof($fp))

{

// Output data

print(fread($fp, $block_size));

flush();

if($rate > 0)

{

// Wait one second before next block if rate is specified

sleep(1);

}

}

// Close the file

fclose($fp);

}

?>

[Via http://freescript4u.wordpress.com]

No comments:

Post a Comment