简体   繁体   中英

Trouble uploading .xml file via PHP

I'm trying to create a form where a user can upload an xml file to my server which will overwrite one that already exists. I'm using the code below (which I know doesn't upload the file if it already exists, but I'll fix that once I've fixed this).

The problem is that the first if statement fails at this statement

($_FILES["file"]["type"] == "application/xml")

meaning that I get an invalid file message. If I comment that out, the file uploads.

Changing the file types allowed to another type (eg jpg) works.

<?php
$allowedExts = array("xml");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "application/xml"))
&& ($_FILES["file"]["size"] < 5000000)
&& 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("xml/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "xml/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "xml/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

I'm very new to PHP so be gentle, I have looked for similar questions but not found anything that seems to fix this issue.

Thanks.

From PHP website:

$_FILES['userfile']['type']

The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

"if the browser provided this information." some browser don't send type. You need validate via extension or parse XML.

Check this.

与它一起工作

($_FILES["file"]["type"] == "text/xml")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM