1

可能重复:
文件上传时多张图片上传数量错误

嘿,所以我有一个将一个文件上传到服务器的 php 脚本,如何更改代码以允许同时上传多个文件。在人们开始链接到其他问题之前,我知道如何搜索 stackoverflow 和谷歌,但是我通过搜索找到的答案我无法弄清楚如何应用于我的代码。我的代码如下:

<?php
session_start();
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
     echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {

echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

if (file_exists($_SESSION['user']."/" . $_FILES["file"]["name"]))
  {
  echo $_FILES["file"]["name"] . " already exists. ";
  }
else
  {
  move_uploaded_file($_FILES["file"]["tmp_name"][$i],
  $_SESSION['user']."/" . $_FILES["file"]["name"]);
  echo "Stored in: " . $_SESSION['user']."/" . $_FILES["file"]["name"];

  }
}



else
  {
  echo "Invalid file";
  }

?> 
4

2 回答 2

1

是我几年前写的一个高级文件上传系统:

HTML:

<form action="upload.php" method="post" enctype="multipart/form-data" >
    <input type="file" name="myfile[]" /><br>
    <input type="file" name="myfile[]" /><br>
    <input type="file" name="myfile[]" /><br>
    <!-- MORE AND MORE -->
    <input type="submit" name="submit" value="Upload" />
</form>

PHP:

<?php // upload.php
// Set timezone for probable usage.
date_default_timezone_set('Asia/Tehran');

// Assign valid types
$valid_mime = array(
    'image/jpeg',
    'image/pjpeg',
    'image/jpeg',            
    'image/png',
    'image/gif'
);

function upload($files, $dir, $size_limit=1024, $prevent_duplicate=false){
    global $valid_mime;

    // $files must be given.
    if(!isset($files)) return false;

    // Look for $valid_mime array.
    isset($valid_mime) and is_array($valid_mime) or die('Error in data resources, valid_mime array not found.');

    // Make directory if not exists. set permission to 0777.
    is_dir($dir) and chmod($dir, 0777) or mkdir($dir, 0777, true);

    $count = 1;
    foreach($files as $file){
        $file['error'] === UPLOAD_ERR_OK or die('Error in uploading file(s).');

        // Check uploaded-file type.
        in_array($file['type'], $valid_mime) or die();

        // Set size_limit in KB.
        $file['size'] > $size_limit*1024 and die('The uploaded file exceeds the maximum file size.');

        // Prevent duplicate filenames.
        $prefix = ($prevent_duplicate == true) ? time().'_' : '';
        $suffix = ($prevent_duplicate == true) ? '_'.$count++ : '';

        $file_extension = strrchr($file['name'], '.');
        $filename = basename($file['name'], $file_extension);

        $file_path = "{$dir}/{$prefix}{$filename}{$suffix}{$file_extension}";

        // Move uploaded-file from php temp folder to desire one.
        move_uploaded_file($file["tmp_name"], $file_path);

        // Make an array of filepaths
        $output[] = $file_path;
    }

    // Change permission of folder according to security issues.
    chmod($dir, 0755);

    return $output; 
}
/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////  Controller Section  ////////////////////////////////

// Assign tmp_arr from $_FILES['myfile'] and do die if there is any problem.
$tmp_arr = (isset($_POST['submit']) and isset($_FILES['myfile'])) ? $_FILES['myfile'] : die('Error in posting data.');

// Create an array with desired structure.
for($i=0; $i<count($tmp_arr['name']); $i++){
    $files[] = array(
        'name'      =>  $tmp_arr['name'][$i],
        'type'      =>  $tmp_arr['type'][$i],
        'tmp_name'  =>  $tmp_arr['tmp_name'][$i],
        'error'     =>  $tmp_arr['error'][$i],
        'size'      =>  $tmp_arr['size'][$i],
    );
}

// size_limit in KB
$path_arr = upload($files, './public', 1024, true);

// SEE WHAT HAPPENS ;)
echo '<pre>';
var_export($path_arr);
?>
于 2012-10-07T15:18:32.313 回答
0

使用这样的东西

<input type="file" name="uploadfile[]" multiple="multiple"/>

你的 php 代码应该是这样的

<?php

foreach ($_FILES['uploadfile']['name'] as $filename) 
            {
                $temp=$target;
                $tmp=$_FILES['file']['tmp_name'][$count];
                $count=$count + 1;
                $temp=$temp.basename($filename);
                move_uploaded_file($tmp,$temp);//add more security as required
                $temp='';
                $tmp='';
            }

?>
于 2012-10-07T15:10:09.137 回答