Page 1 of 1

Automatically downloading a file

Posted: Thu Sep 25, 2003 3:19 pm
by SBukoski
I have some code which creates a text file on the server. How do I make it so the download popup window appears for downloading this file. Having it just as a link will open it in the browser, and I don't want my users to have to right click and "save as" to get it.

Any ideas?

Posted: Thu Sep 25, 2003 6:03 pm
by Unipus
I believe that's all totally dependent on the MIME types set up on the server. So, you could de-register the MIME for .txt files, and then the site will no longer attempt to display them, but this might have unintended consequences elsewhere. And if you're using shared hosting, this obviously isn't an option.

A better option might be to give your text files a different extension (unrecognized by the server, unused elsewhere). Of course, that just moves the problem client-side, because then your users have to know how to open them.

Posted: Thu Sep 25, 2003 9:34 pm
by SBukoski
I've tried several different file extensions. It always seems to open it in the browser no matter the file extension. I'll probably just end up putting instructions up on how to download it by right clicking. It's only a small hassle and shouldn't bother people too much.

But if anybody knows of a way, speak up. :)

Posted: Fri Sep 26, 2003 5:01 am
by JayBird
easy, just use this code and change the paths, and the application/pdf MIME to the MIME for text files.

Code: Select all

<?

	// Get the filename from the query string of the file we want to download
	$fileName = $_GET["file"];
	
	// The full path to our downloads directory
	$fileDir = "/full?path/to/download/directory";
	
	// Combine the filename and the path
	$path = "$fileDir$fileName";
	
	
	////////////////////////////////////////
	/* Force browser to download the file */
	////////////////////////////////////////

	global $HTTP_USER_AGENT;
	$file = basename($path);
	$size = filesize($path);
	header("Content-Type: application/octet-stream");
	header("Content-Type: application/pdf");
	header("Content-Length: $size");
           
	// IE5.5 just downloads index.php if we don't do this
	if(preg_match("/MSIE 5.5/", $HTTP_USER_AGENT)) {
		 header("Content-Disposition: filename=$file");
	} else {
		header("Content-Disposition: attachment; filename=$file");
	}
    header("Content-Transfer-Encoding: binary");
    $fh = fopen($path, "r");
    fpassthru($fh);

?>
then do a link like

Code: Select all

&lt;a href="/download_script.php?file=your_textfile.txt"&gt;Click here to download file&lt;/a&gt;
Mark

Posted: Fri Sep 26, 2003 9:01 am
by SBukoski
Thanks a ton, that did the trick for me!