Specifications

echo “Preview of uploaded file contents:<br><hr>”;
echo $contents;
echo “<br><hr>”;
?>
</body>
</html>
<?
// This function is from the PHP manual.
// is_uploaded_file is built into PHP4.0.3.
// Prior to that, we can use this code.
function is_uploaded_file($filename) {
if (!$tmp_file = get_cfg_var(‘upload_tmp_dir’)) {
$tmp_file = dirname(tempnam(‘’, ‘’));
}
$tmp_file .= ‘/’ . basename($filename);
/* User might have trailing slash in php.ini... */
return (ereg_replace(‘/+’, ‘/’, $tmp_file) == $filename);
}
?>
Interestingly enough, most of this script is error checking. File upload involves potential secu-
rity risks, and we need to mitigate these where possible. We need to validate the uploaded file
as carefully as possible to make sure it is safe to echo to our visitors.
Lets go through the main parts of the script.
First, we check whether $userfile is “none”. This is the value set by PHP if no file was
uploaded. We also test that the file has some content (by testing that
$userfile_size is greater
than
0), and that the content is of the right type (by testing $userfile_type).
We then check that the file we are trying to open has actually been uploaded and is not a local
file such as
/etc/passwd. Well come back to this in a moment.
If that all works out okay, we then copy the file into our include directory. We use
/home/book/uploads/ in this exampleits outside the Web document tree, and therefore a
good place to put files that are to be included elsewhere.
We then open up the file, clean out any stray HTML or PHP tags that might be in the file using
the strip_tags() function, and write the file back.
Advanced PHP Techniques
P
ART IV
356
LISTING 16.2 Continued
21 7842 CH16 3/6/01 3:40 PM Page 356