Site With The Lamp

A LAMP Portal


Linux
Java
PHP


Blog
etc

The totally Rad Software Company - Sponsor

New Articles

On Jabber.

JSP File upload progres bar.

LPI Certification

Directory Browsing with PHP.

In the previous pages you have seen how easy it is to list the contents of a directory using the backticks operator in PHP.

Now we will take a shot at delivering these files safely to the user. Two PHP functions need to be used for this. The first is the passthru() function which allows the contents of a file to be directly sent to the browser. The second is the header() function which allows you to specify HTTP headers such as content type.

As usually happens browsers don't always follow standards. So our file delivery mechanism needs to inspect the $HTTP_USER_AGENT variable to detect which browser is being used. The next snippet of code shows how you can set the appropriate headers for the two most commonly used browsers.

	$mime_type = (strstr($HTTP_USER_AGENT,'IE') || strstr($HTTP_USER_AGENT,'OPERA'))
	? 'application/octetstream'
	: 'application/octet-stream';
	// finally send the headers and the file
	header('Content-Type: ' . $mime_type);
	header('Expires: ' . $now);

	if (strstr($HTTP_USER_AGENT,'IE')) {
		header('Content-Disposition: inline; filename="' . $filename. '"');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
	} else {
		header('Content-Disposition: attachment; filename="' . $filename .'"');
		header('Pragma: no-cache');
	}

download full source

A word of warning: The source code that's included in this article is by no means fully secure you need to plug in a user authentication system if you plan to use it on a production enviorenment. You would also have to set very strict file permissions on your server so that users don't browse other people's folders

This code will eventually make it's way into Megaupload - the php fileuploader with progress bar. It's being used in the recently added article on creating an FTP client with PHP.