note 24686 added to function.fread

From: Date: Sun, 25 Aug 2002 19:06:04 +0000
Subject: note 24686 added to function.fread
Groups: php.notes 
Request: Send a blank email to php-notes+get-35602@lists.php.net to get a copy of this message
Please remove my previous entry - the following entry corrects some minor errors, which would cause problems with a few download managers... Here's a function for sending a file to the client - it may look more complicated than necessary, but has a number of advantages over simpler file sending functions: - Works with large files, and uses only an 8KB buffer per transfer. - Stops transferring if the client is disconnected (unlike many scripts, that continue to read and buffer the entire file, wasting valuable resources) but does not halt the script - Returns TRUE if transfer was completed, or FALSE if the client was disconnected before completing the download - you'll often need this, so you can log downloads correctly. - Sends a number of headers, including ones that ensure it's cached for a maximum of 2 hours on any browser/proxy, and "Content-Length" which most people seem to forget. Note that the folder from which protected files will be pulled, is set as a constant in this function (/protected) ... Now here's the function: function send_file($name) { $status = FALSE; $path = "protected/".$name; if (!is_file($path) or connection_status()!=0) return(FALSE); header("Content-type: application/octet-stream"); header("Content-Disposition: inline; filename=\"".$name."\""); header("Content-length: ".(string)(filesize($path))); header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); if ($file = fopen($path, 'rb')) { while(!feof($file) and (connection_status()==0)) { print(fread($file, 1024*8)); flush(); } $status = (connection_status()==0); fclose($file); } return($status); } And here's an example of using the function: if (!send_file("platinumdemo.zip")) { die ("file transfer failed"); // either the file transfer was incomplete // or the file was not found } else { // the download was a success // log, or do whatever else } Regards, Rasmus Schultz -- http://www.php.net/manual/en/function.fread.php http://master.php.net/manage/user-notes.php?action=edit+24686 http://master.php.net/manage/user-notes.php?action=delete+24686 http://master.php.net/manage/user-notes.php?action=reject+24686

« previous php.notes (#35602) next »