note 24249 deleted from function.fread by spic

From: Date: Mon, 26 Aug 2002 13:10:30 +0000
Subject: note 24249 deleted from function.fread by spic
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-35664@lists.php.net to get a copy of this message
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 never cached on the client side in any browser, and "Content-Length" which most people seem to forget Now here's the function: function send_file($name) { $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: Mon, 12 Dec 2001 08:00:00 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(); } return(connection_status()==0); fclose($file); } else { return(FALSE); } } 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

« previous php.notes (#35664) next »