2

PHP FILE :
This is my form action file in php.
I am successful in uploading images but text files are producing 'Invalid File Error'.
What may be the error and how to resolve it?

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png", "txt");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "text/txt"))
&& ($_FILES["file"]["size"] < 20000000)
&& 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("C:/inetpub/wwwroot/" . $_FILES["file"]["name"]))
  {
  echo $_FILES["file"]["name"] . " already exists. ";
  }
else
  {
  move_uploaded_file($_FILES["file"]["tmp_name"],
  "C:/inetpub/wwwroot/" . $_FILES["file"]["name"]);
  echo "Stored in: " . "C:/inetpub/wwwroot/" . $_FILES["file"]["name"];
  }
}
  }
else
  {
     echo "Invalid file";
  }
?> 

Thanks in advance.

2
  • 1
    You should consider changing $_FILES["file"]["type"] == "text/txt" to $_FILES["file"]["type"] == "text/plain" also what do you get when you print $_FILES["file"]["type"] for text files ? Commented Aug 7, 2013 at 11:30
  • Yeah you are correct. Commented Aug 7, 2013 at 11:40

2 Answers 2

5

I don't think your mime type for .txt files is correct. You could try txt/plain instead of txt/text in your IF statement.

Sign up to request clarification or add additional context in comments.

Comments

1

Use the below code:

|| ($_FILES["file"]["type"] == "text/plain"

Instead of

|| ($_FILES["file"]["type"] == "text/txt"

Here is the list of mime-content-type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.