php upload multiple files

2019-05-20 14:02发布

Im not super familiar with PHP, I have the following code which allows me to upload a file to the server. how can I make this upload multiple files, in my html I have already added the multiple property. the php code is this:

<?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";
  }

?>

2条回答
Bombasti
2楼-- · 2019-05-20 14:38

Try this

$file = $_FILES['image_file'];
for($i = 0; $i < count($file['name']); $i++){
    $image = array(
        'name' => $file['name'][$i],
        'type' => $file['type'][$i],
        'size' => $file['size'][$i],
        'tmp_name' => $file['tmp_name'][$i],
        'error' => $file['error'][$i]
    );
    // Validate, upload, and save to the DB
}

This way, you've got a file "$image" exactly as if it was just one file selected, now you need to handle that file by using your code to upload your file. So for each '$_FILES' in your code just replace '$image'

查看更多
ゆ 、 Hurt°
3楼-- · 2019-05-20 14:57

Multiple files can be selected and then uploaded using the

<input type='file' name='file[]' multiple>

The sample php script that does the uploading:

<html>
<title>Upload</title>
<?php
    session_start();
    $target=$_POST['directory'];
        if($target[strlen($target)-1]!='/')
                $target=$target.'/';
            $count=0;
            foreach ($_FILES['file']['name'] as $filename) 
            {
                $temp=$target;
                $tmp=$_FILES['file']['tmp_name'][$count];
                $count=$count + 1;
                $temp=$temp.basename($filename);
                move_uploaded_file($tmp,$temp);
                $temp='';
                $tmp='';
            }
    header("location:../../views/upload.php");
?>
</html>

The selected files are received as an array with

$_FILES['file']['name'][0] storing the name of first file. $_FILES['file']['name'][1] storing the name of second file. and so on.

查看更多
登录 后发表回答