Page 1 of 1

Downloading files with PHP

Posted: Thu Nov 01, 2007 7:34 pm
by Mr Tech
I've created a script that allows users to download files to their pc using PHP... However, it seems to be corrupting PDF files. The PDF files open ok when you open them direct into the browser or on my pc, but when I use the PHP code, it says it's corrupt. This was my original code:

Code: Select all

$filesize = filesize("files/".$fileinfo[file]);
header("Content-Disposition: attachment; filename=\"".$fileinfo[file]."\"");
header("Content-type: application/octet-stream");
header("Content-Length: ".$filesize);
readfile("files/".$fileinfo[file]);
I then tried a class that made one of the PDFs download ok but one other still said it was corrupted...

Code: Select all

<?
/*
 * Class has simple interface to download any file from a server
 * without displaying the location of the file
 *
 * Author: Viatcheslav Ivanov, E-Witness Inc., Canada;
 * mail: ivanov@e-witness.ca;
 * web: http://www.e-witness.ca; http://www.coolwater.ca; http://www.strongpost.net;
 * version: 1.1 /08.19.2002
 *
 */

if ( !defined("DOWNLOADFILE_H") ) {

	define("DOWNLOADFILE_H",1);

	class DOWNLOADFILE {
		var $df_path = "";
		var $df_contenttype = "";
		var $df_contentdisposition = "";
		var $df_filename = "";

		function DOWNLOADFILE($df_path, $df_contenttype = "application/octet-stream", $df_contentdisposition = "attachment", $df_filename = "") {
			$this->df_path = $df_path;
			$this->df_contenttype = $df_contenttype;
			$this->df_contentdisposition = $df_contentdisposition;
			$this->df_filename = ($df_filename)? $df_filename : basename($df_path);
		}

		// check is specified file exists?
		function df_exists() {
			if(file_exists($this->df_path)) return true;
			return false;
		}

		// get file size
		function df_size() {
			if($this->df_exists()) return filesize($this->df_path);
			return false;
		}

		// return permission number for user 'other'
		function df_permitother() {
			return substr(decoct(fileperms($this->df_path)),-1);
		}

		// download file
		function df_download() {
			if($this->df_exists() && $this->df_permitother() >= 4) {
				header("Content-type: ".$this->df_contenttype);
				header("Content-Disposition: ".$this->df_contentdisposition."; filename=\"".$this->df_filename."\"");
				header("Content-Length: ".$this->df_size());

				$fp = readfile($this->df_path, "r");
				return $fp;
			}
			return false;
		}

	}

} //if ( !defined("DOWNLOADFILE_H") )

?>
Is there anything I am doing wrong? I noticed the above class is very old (2002) so maybe that's why?

Appreciate your help.

Posted: Thu Nov 01, 2007 8:02 pm
by Christopher
Change the Content-type to "'application/pdf" and it should fix the problem.

Posted: Thu Nov 01, 2007 8:23 pm
by Mr Tech
Christopher, you're a flippin legend mate!