Page 2 of 2

Posted: Thu Nov 29, 2007 10:09 am
by RobertGonzalez
Your upload dir, can you reference it using a *nix type path reference? Try this code and see if it does anything for you (make a directory inside of the directory where this code lives called "upload".

Code: Select all

<?php
require_once 'directory-iterator.php';
$link = '<a href="%s">%s</a><br />';
$uploaddir = './uploads/';
$message = '';
$success = false;

if (isset($_POST['doUpload'])) {
  // Need the file extension when renaming
  $upload_file = $_FILES['userfile']['name'];
  $ext = '.' . substr(strrchr($upload_file, "."), 1);
  
  if (!empty($_POST['newfilename'])) {
    $filename = $_POST['newfilename'] . $ext;
  } else {
    $filename = basename($upload_file);
  }
  
  $uploadfile = $uploaddir . $filename;
  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    $success = true;
    $message =  "File <b>$filename</b> is valid, and was successfully uploaded to <b>$uploaddir</b>.\n";
  } else {
    $message =  "File <b>$filename</b> was not uploaded. It is possible there was a file upload attack!\n";
  }
}
?>
<html>
<head><title>File Upload Tests</title></head>

<body>
<!-- The data encoding type, enctype, MUST be specified as below -->
<?php $d = DirTree(new RecursiveDirectoryIterator($uploaddir)); if (!empty($d)): ?>
<h2>What has been uploaded already</h2>
<?php foreach ($d as $k => $v): if (!is_array($v)) echo sprintf($link, $uploaddir.$k, $k) . "\n"; endforeach; endif; ?>
<h2>Upload a file</h2>
<?php if (!empty($message)): ?>
<p style="color: <?php echo $success ? '#080' : '#f33'; ?>;"><?php echo $message; ?></p>
<?php endif; ?>
<form enctype="multipart/form-data" action="<?php echo basename(__FILE__); ?>" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="800000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" /><br />
	New filename: <input type="text" name="newfilename" maxlength="20" />
    <input type="submit" name="doUpload" value="Send File" />
</form>
</body>
</html>
directory-iterator.php (I believe this is a feyd creation):

Code: Select all

<?php
function DirTree(RecursiveDirectoryIterator $dir)
{
  $tree = array();
  $dirs = array(array($dir, &$tree));
  
  for($i = 0; $i < count($dirs); ++$i) {
    $d =& $dirs[$i][0];
    $tier =& $dirs[$i][1];

    for($d->rewind(); $d->valid(); $d->next()) {
      if ($d->isDir()) {
        $tier[$d->getFilename()] = array();
        $dirs[] = array($d->getChildren(), &$tier[$d->getFilename()]);
      } else {
        $tier[$d->getFilename()] = $d->getSize();
      }
    }
  }

  return $tree;
}
?>