The following is a rewrite of David Grant’s updown, a simple little utility that will take a file POSTed to it and write it to a local file. It also prints all of the files in the given directory it is in. I’ve rewritten it to work without requiring register_globals being turned on, and cleaned it up, as well as making it output valid HTML.
This was done primarily to help someone out who is just learning PHP. I wouldn’t suggest anyone really adhere to this coding style, as it can be quite painful. ;)
It uses move_uploaded_file, so it requires PHP 4.0.3 or higher. It does simple globbing to only allow specific filetypes – look below.
< ?php // This is a very, very, very simple file upload utility written in PHP.. // Title of web page $title=”My Spiffy Upload Site”; // Size in bytes of maximum upload size $maxfilesize=”100000”; // curdir is hardcoded to the ‘current directory’, for obvious reasons. $curdir=getcwd(); // Files with the given extensions will be listed $fyletypes=strtolower(“gif|jpg|tiff|tif|png”); // STOP DO NOT EDIT BELOW THIS LINE! $getdir=array(); $thescript=$_SERVER[‘PHP_SELF’]; $stemp=pathinfo($thescript); $scriptbase=$stemp[“basename”];// I should do this better. Really, I should.
if ($_FILES) {
$tmpfyle=$_FILES[‘fyle’][‘tmp_name’];
$thefyle=$_FILES[‘fyle’][‘name’];
$destfyle=”$curdir/$thefyle”;
// Kind of stupid. If $tmpfyle, $destfyle are set, move, and force refresh
// back to ourselves, rather than having a whole massive parsing routine,
// et al.
if (preg_match(”/.($fyletypes)$/”, strtolower($destfyle))) {
if (is_file($destfyle)) {
// Sometimes, I remind myself why simple things are never simple.
unlink($tmpfyle);
exit(“
Cowardly refusing to overwrite file: $destfyle!
”); } else { move_uploaded_file($tmpfyle, $destfyle); header(“location: $thescript”); }} else { unlink($tmpfyle); exit(“
File $destfyle is not allowed!
”);}
}
? >
< ?php
echo “
// Get our file listing. Don’t rely on globbing or anything fancy.
$handle=opendir(”$curdir”);
while ($file = readdir($handle))
$getdir[count($getdir)] = $file;
closedir($handle);
sort($getdir);
// Print the file names
foreach($getdir as $fyle) {
if (($fyle!=”.”) && ($fyle!=”..”)) {
if (($scriptbase!=$fyle) && ($fyle!=”index.php”) && is_file($fyle) &&
preg_match(”/.($fyletypes)$/”, strtolower($fyle))) {
$thefilesize=filesize(”$curdir/$fyle”);
echo ”· $fyle ”;
echo ”($thefilesize bytes)
”;
}
}
}
? >