在php中上传文本文件,如何做和安全措施

I need HTML and PHP that allows the user to upload a text file.

I have heard that one should be careful with functions that allow users to upload their own files because people can inject malicious software and code. Let's say my website only allows MS Word on Mac and Windows, what will the code look like and what code should I use to prevent malicious software injections? The file can maximum be 1MB.

This is what I currently have:

HTML

<html>
<body>
    <form action="uploadtextfile.php" enctype="multipart/form-data" method=
    "post">
        <label for="file">Filename:</label> <input id="uploadedtextfile" name=
        "textfile" type="file"><br>
        <input name="submit" type="submit" value="Send!">
    </form>
</body>
</html>

I have no idea what PHP code to use, but according to W3Cschools.com it should look something like this:

<?php
    if ($_FILES["file"]["error"] > 0) {
        echo "Error: ".$_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 "Stored in: ".$_FILES["file"]["tmp_name"];
    } 
?>

How am I supposed to form the code so it is safe to use and only accepts MS Word files that are maximum 1MB?

First of all list all allowed MS Word extensions in an array.

$allowedExts = array('doc', 'docx');

Use pathinfo to get the extension of the file

$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);

check if that extension exists in the array you created If yes then you check the size of that file within the condition.

if (in_array($extension, $allowedExts))
{
  if (($_FILES["file"]["size"] / 1024) <= 1024)
  {
     // File upload code goes here
  }
}

That you should work, i haven't tried it out myself yet.