开发者

php multiple file upload

I have a script I'm working out to upload up to 10 files at once. I have 10 seperate inputs in my html:

  <?php
    for($i=0;$i<10;++$i) {
         $num = $i+1;
         echo '
            <span>'.$num.'</span><input type="file" name="photo'.$i.'" />
              ';
     }
  ?>

And then I have my uploader which I have used before--in a slightly different form--but can't get to work now:

$path = "../path/to/folder/";
for($i = 0; $i < 20; $i++){
  $fileName = "photo". "$i";
  $filePath = "$path". "photo$i.jpg";

  if (!empty($_FILES['$fileName']['tmp_name'][$i])) {
       if (!copy($_FILES['$fileName']['tmp_name'][$i], $filePath)) {
            echo "failed to save '.$filePath.'";
        }
       chmod($filePath, 0644);
     }
 }

In a working version of this script I cut the for loop and just numbered each upload individually (I had this piece of code without the loop 1开发者_运维百科0 times each with its own number). That worked great but it's really pretty ugly to look at a piece of code like that. Any ideas how to make this work?

UPDATED:

Still not having any luck I appreciate all the help. I think my problem lies in that the $_FILES arrays aren't being populated properly edits as follows:

changed HTML to:

  <?php
    for($i=0;$i<10;++$i) {
         $num = $i+1;
         echo '
            <span>'.$num.'</span><input type="file" name="photo[]" />
              ';
     }
  ?>

and the uploader script to:

$path = "../path/to/folder/";
for($i = 0; $i < 20; $i++){
  $fileName = "photo". "$i";
  $filePath = "$path$fileName.jpg";

  if (!empty($_FILES["photo"]["tmp_name"][$i])) {
       if (!copy($_FILES["photo"]["tmp_name"][$i], $filePath)) {
            echo "failed to save '.$filePath.'";
        }
       chmod($filePath, 0644);
     }
 }


You are using $i twice:

$_FILES["$fileName"]["tmp_name"][$i]

the [$i] part makes no sense to me: You are already accessing each element through $fileName. I think you need to simply get rid of [$i].


I believe (part of) your problem is the quoting. You are using single quotes in your loop which is causing the variables to not be evaluated. Try using the code below instead. There may be some other issues, but that should solve one aspect of your problem.

$path = "../path/to/folder/";
for($i = 0; $i < 20; $i++){
  $fileName = "photo". $i;
  $filePath = "$path". "$fileName.jpg";

  if (!empty($_FILES["$fileName"]['tmp_name'][$i])) {
       if (!copy($_FILES["$fileName"]['tmp_name'][$i], $filePath)) {
            echo "failed to save $filePath";
        }
       chmod($filePath, 0644);
     }
 }


you have overcomplicated it
while nothing can be easier
just foreach over $_FILES

foreach ($_FILES as $file) {
  $filePath = $path. "photo".($i++).".jpg";
  if (!$file['error']) {
    move_uploaded_file($file['tmp_name'], $filePath));
  }
}

that's all for for the first naming convention.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜