Forum Moderators: coopster

Message Too Old, No Replies

Serving a file from outside the document tree

         

syndeticFT

9:37 pm on Feb 3, 2006 (gmt 0)

10+ Year Member



If I want the user to see a picture or file that comes from a directory that is within the html document tree I just output a link like

echo "\n<BR><a href=$pathandfile><B>$file</B></a>";
The user can click on the link and see the file.

A very important thing to note is that it does not matter what type the file is the browser opens the appropriate viewer. It can be a JPEG or a word doc or a pdf or whatever.

But what if the path points to a location that is outside the html document tree?

I presume that I have to put a link to a PHP script
For example
echo "\n<BR><a href=file_serve.php?filename>$file</a>";

Then that script would read the file from outside the document tree
read the file into a variable and then write it to a user. If the file is a jpeg then I can use
ImageJPEG($img);
to send it to the user.

But I would like it to make it general so that no matter what the file type is, it still works the same as the simple link I showed above.

here is a PHP script that will serve a jpeg but how do I make it general

<?PHP
// IMAGE_SERVE_FILE.PHP
// This script serves a image from a file.
//
// Note that you cant echo any debug comments from in this routine.

//$path_and_file = "../files_dir/text_file.txt";
$path_and_file = "../files_dir/187-8727b_img.jpg";
$path_and_file = "../files_dir/This is a word document.doc";

// Replace any spaced in the file name with %20 code
$path_and_file = str_replace(" ","%20",$path_and_file);
//echo "path_and_file = $path_and_file ";

// I think we need to read the file into a variable and then
// write it out

$handle = fopen($path_and_file, "rb");

// Send the header that is appropriate for a jpeg
header("Content-Type: image/jpeg");
header("Content-Length: " . filesize($path_and_file));

// dump the picture and stop the script
fpassthru($handle);

// But how do we make this general for text, doc, pdf, and all other file extensions

?>

Thanks in advannce.

StupidScript

10:05 pm on Feb 3, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Fun stuff!

As a first note, you can use

urlencode()
instead of
str_replace
to produce a reliably encoded string.

On to the meat ...

For image files (not PDF), you can use

getimagesize()
to return an array of image properties, like the MIME-type, and then use that info to write your headers.

From the manual [us2.php.net]:

Example 3. getimagesize() and MIME types
<?php

$size = getimagesize($filename);

$fp=fopen($filename, "rb");

if ($size && $fp) {

header("Content-type: {$size['mime']}");

fpassthru($fp);

exit;

} else {

// error

}

?>

If your PHP is compiled

[i]--with-mime-magic[/i]
then you also have
[url=http://us2.php.net/manual/en/function.mime-content-type.php]mime_content_type()[/url]
available to you for getting pretty much any MIME-type.