Skip to content

Instantly share code, notes, and snippets.

@tomkrush
Created March 18, 2010 05:19
Show Gist options
  • Save tomkrush/336074 to your computer and use it in GitHub Desktop.
Save tomkrush/336074 to your computer and use it in GitHub Desktop.
// This is pulled from Kohana. You should be able to extract the basic concept of it and implement it in CodeIgniter
public function send_file($filename, $download = NULL, array $options = NULL)
{
if ( ! empty($options['mime_type']))
{
// The mime-type has been manually set
$mime = $options['mime_type'];
}
if ($filename === TRUE)
{
if (empty($download))
{
throw new Kohana_Exception('Download name must be provided for streaming files');
}
if ( ! isset($mime))
{
// Guess the mime using the file extension
$mime = File::mime_by_ext(strtolower(pathinfo($download, PATHINFO_EXTENSION)));
}
// Get the content size
$size = strlen($this->response);
// Create a temporary file to hold the current response
$file = tmpfile();
// Write the current response into the file
fwrite($file, $this->response);
// Prepare the file for reading
fseek($file, 0);
}
else
{
// Get the complete file path
$filename = realpath($filename);
if (empty($download))
{
// Use the file name as the download file name
$download = pathinfo($filename, PATHINFO_BASENAME);
}
// Get the file size
$size = filesize($filename);
if ( ! isset($mime))
{
// Get the mime type
$mime = File::mime($filename);
}
// Open the file for reading
$file = fopen($filename, 'rb');
}
// Inline or download?
$disposition = empty($options['inline']) ? 'attachment' : 'inline';
// Set the headers for a download
$this->headers['Content-Disposition'] = $disposition.'; filename="'.$download.'"';
$this->headers['Content-Type'] = $mime;
$this->headers['Content-Length'] = $size;
if ( ! empty($options['resumable']))
{
// @todo: ranged download processing
}
// Send all headers now
$this->send_headers();
while (ob_get_level())
{
// Flush all output buffers
ob_end_flush();
}
// Manually stop execution
ignore_user_abort(TRUE);
// Keep the script running forever
set_time_limit(0);
// Send data in 16kb blocks
$block = 1024 * 16;
while ( ! feof($file))
{
if (connection_aborted())
break;
// Output a block of the file
echo fread($file, $block);
// Send the data now
flush();
}
// Close the file
fclose($file);
// Stop execution
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment