• Home
  • Blog
  • Lifestream
  • Me
  • Twitter

Recent Posts

  • » Google Car - Damn I'm Observant
  • » Travelling - What's Next?
  • » Posh East Perth Apartment
  • » House in Perth
  • » House Sitting in Adelaide
  • » Sailing The Whitsundays
  • » Agnes Water / 1770
  • » Fraser Island
  • » Coomera Springs and Noosa
  • » Byron Bay

Tags

  • 365  australia  code  experiences  explore  flickr  france  function  holiday  house  javascript  misc  movie  perth  photo  photography  photos  php  random  rant  review  ski  skiing  thailand  traveling  travelling  trekking  video  work 

Search


Links

  • » 365 Gallery
  • » Twitter
  • » Lifestream
  • » My Flickr

Archives

  • » January 2010 (1)
  • » November 2009 (2)
  • » August 2009 (2)
  • » June 2009 (2)
  • » May 2009 (5)
  • » April 2009 (6)
  • » March 2009 (4)
  • » February 2009 (1)
  • » January 2009 (2)
  • » December 2008 (3)
  • » November 2008 (2)
  • » October 2008 (2)
  • » September 2008 (5)
  • » August 2008 (3)
  • » July 2008 (1)
  • » June 2008 (2)
  • » April 2008 (10)
  • » March 2008 (7)
  • » February 2008 (5)
  • » January 2008 (9)
  • » December 2007 (2)

 RSS Feed

Search results for 'header'

PHP Force Download

April 22nd, 2008
So today I needed to force a file to download in a web browser where the browser would normally just output the file. It will also work in IE6 over a secure (HTTPS) connection.. which was a bit like hard work.

function forceDownload($file,$name=false,$contenttype="application/octet-stream",$delete=false){
	if (!$name) $name = $file;
	
	header("Cache-Control: public, must-revalidate");
	header("Pragma: hack");
	header("Content-Type: " . $contenttype);
	header("Content-Length: " .(string)(filesize($file)) );
	header('Content-Disposition: attachment; filename="'.basename($name).'"');
	header("Content-Transfer-Encoding: binary\n");
					  
	$fp = fopen($file, 'rb');
	$buffer = fread($fp, filesize($file));
	fclose ($fp);
	echo $buffer;
	if ($delete){
		unlink($file);
	}
}

Example Usage:
So I wanted to create a temporary file, write some contents to it then force the file to be outputted via the browser and deleted on completion of download.
$data = 'what a load of content';    // data to write to a file

$filename = 'cache/tmpfile.txt';     // the file to write the data too, must be writable
file_put_contents($filename,$data);  // write the data to the file

// force the download and delete the file afterwards
forceDownload($filename,'whateverfilenameyoulike.txt','text/plain',true);

No Comments »
.
 
Twitter   |   Contact “everything should be made as simple as possible, but no simpler ” - Albert Einstein