note 72259 rejected from function.fread by nlopess
| From: | nlopess@php.net | Date: | Tue, 09 Jan 2007 23:40:20 +0000 |
| Subject: | note 72259 rejected from function.fread by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-121512@lists.php.net to get a copy of this message | ||
Note Submitter: dfens270 at hotmail dot com
----
Using wget -Sc http://www.example.com/file the examples
below dont return the correct md5 for a file. This can be important for some people to get the exact
data. I've tested this and it works especially for partial resuming and full content transfers.
If anyone can find a bug in it please send me an email.
The main point for these things is to note the range issues. I think what I have is correct at the
moment.
Also as a side note like alot of people have said, monitor the user if the disconnected
connection_status(), no one likes seeing a server wasting resources.
<?php
//http://www.vbip.com/winsock/winsock_http_08_01.asp
//take careful note from there. alot of examples arent doing the correct range of filesize(bytes)-1
function send($handle) {
$handle = realpath($handle);
$size = filesize($handle);
$start = 0;
set_magic_quotes_runtime(0);
//set_time_limit(0);
header('Content-Type: ' . mime_content_type($handle));
header('Content-Disposition: attachment; filename="' . basename($handle) .
'"');
header('Accept-Ranges: bytes');
//header('Content-Transfer-Encoding: binary');
//resume partial content
if(isset($_SERVER['HTTP_RANGE'])) {
//get start and end of bytes
list($a, $range) = explode('=', $_SERVER['HTTP_RANGE']);
list($start, $end) = explode('-', $range);
//some malformed header
if(!isset($start) && !isset($end)) {
return false;
}
//missing range of bytes
if(!isset($start)) { //only the end bytes are there
$start = $size - $end;
$end = $size - 1;
}else { // only the start bytes are there
$end = $size - 1;
}
//if start is less than zero
$start = $start < 0 ? 0 : $start;
//if end is greater than the file size
$end = $end > $size - 1 ? $size - 1 : $end;
//the length of bytes is the end-start+1
$length = $end - $start + 1;
//if the length is less than 0 everything is wrong
if ($length < 0) {
return false;
}
//the partial header
header('HTTP/1.1 206 Partial Content');
//not the file size but new partial length
header('Content-Length: ' . $length);
//the range for the client to download
header("Content-Range: bytes $start-$end/$size");
} else {
header('HTTP/1.1 200 OK');
header('Content-Length: ' . $size);
$start = 0;
$end = $size - 1;
}
//echo file_get_contents($handle);
if(false === ($fp = fopen($handle, 'rb'))) {
return false;
}
fseek($fp, $start);
do {
$buf = fread($fp, 1024*8);
$sent += strlen($buf);
echo $buf;
ob_flush();
flush();
} while(!feof($fp) && (connection_status() == 0) );
fclose($fp);
}
?>