PHP File Upload Script

Code for file upload in PHP

 
      <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Upload using PHP</title>
</head>
<body>
  <form action="test.php" method="post" enctype="multipart/form-data">
  <label for="fileupload">Select your File and upload</label> <br>
  <input type="file" name="inputfile" id="inputfile">
  <input type="submit" name="submit" value="Upload">
  <label for="msg" id="msg"></label>
  </form>
<?php
  if(isset($_POST['submit']))
  {
   // echo $_FILES['inputfile']['name']."<br>";
   /* echo $_FILES['inputfile']['type']."<br>";
    echo $_FILES['inputfile']['size']."<br>";
    echo $_FILES['inputfile']['tmp_name']; */
  //  echo basename($_FILES["inputfile"]["name"]);
    /* $target_dir = "uploaded_files/";
    $target_file = $target_dir.basename($_FILES["inputfile"]["name"]);
    $extensiontype = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    echo $extensiontype; */

    $target_dir = "uploaded_files/"; //upload folder
    $target_file = $target_dir.basename($_FILES["inputfile"]["name"]); //file path
   // echo $target_file."<br>";
    $extensiontype = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); //getting the extension of the file
    //echo $extensiontype;

    $extensions = array("docx","doc","pdf");
    $error=0;
    //checking if the file falls within those extensions
    if(!in_array($extensiontype,$extensions))
    {
        echo "only word and pdf files allowed";
        $error=1;
    }

    //checking if file already exists in the folder 
    if(file_exists($target_file))
    {
        echo "File already Exists. Can't Upload";
        $error=1;
    }

    //checking the file size is greater than 5MB
    if($_FILES['inputfile']['size']>5000000)
    {
        echo "File Size greater than 5MB. Upload a file less than 5 MB";
        $error=1;
    }

    //moving file from tmp directory to folder if no errors exist 
    if($error==0)
    {
        move_uploaded_file($_FILES['inputfile']['tmp_name'],$target_file);
        echo $_FILES['inputfile']['name']. "has been uploaded to the server successfully";
    }
  }
?>
</body>
</html>
    
Output

Enter the Program title here

 
      copy and paste the code here
    
Output