'PHP File upload script redirects to the error page when there shouldn't be an error or there is no an error

I have a problem with my PHP file upload script. When I try to press the upload button, it redirects me to the error page "errors/uploadfail.html". But the file selection dialog stays open. I would like to solve the issue that redirects to the error page.

upload.php

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$ip = $_SERVER['REMOTE_ADDR'];
$handle = fopen("logs/log.txt", "a"); 

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    $uploadOk = 1;
  } else {
    header("Location: errors/mimetype.html");
    $uploadOk = 0;
  }
}

// Check if file already exists
if (file_exists($target_file)) {
  header("Location: errors/alreadyexists.html");
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 10000000) {
  header("Location: errors/mimetype.html");
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  header("Location: errors/alreadyexists.html");
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  header("Location: errors/uploadfail.html");
// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
      echo "http://localhost/upload/".$target_file;
    echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
  fwrite($handle, "IP: $ip \r\n");
  fwrite($handle, "FILENAME: $target_file \r\n");
  fwrite($handle, "DATE: ".date("m/d/Y")."\r\n");
  fwrite($handle, "TIME: ".date("h:i A")."\r\n");
  fwrite($handle, "---- \r\n");
  fclose($handle);
  header("Location: success.html?path=".$target_file );
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
?>

index.html

<!DOCTYPE html>
<head>
  <style type="text/css">
      @import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');
      body, html {
          margin: 0;
          padding: 0;
          overflow: hidden;
          background-color: black;
          font-family: 'Montserrat', sans-serif;
      }
      #vanta {
          width: 100%;
          height: 100vh;
          text-align: center;
      }
      .centered {
          position: fixed;
         top: 50%;
        left: 50%;
        margin-top: -50px;
        margin-left: -50px;
}
  </style>
  <link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
  <script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/vanta@latest/dist/vanta.trunk.min.js"></script>
</head>
<html>
<body>
<div id="vanta">



<form action="upload.php" method="post" enctype="multipart/form-data">
  <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  <span style="font-size: 1.2em;"><b>Select image to upload.
  Maximum file size is 10 MB.</b>
  <br><br><br><br><br><br><br><br><br><br><br><br><br>
  <button style="cursor:pointer" style="background: transparent; " onclick="selectfile()" id="upbtn"><img class="centered" src="https://media.discordapp.net/attachments/906303123419693066/961061738512515082/Untitled_drawing_2.png" width="100px"></button>
  <input type="file" style="display:none; visibility: hidden;" name="fileToUpload" allow=".gif,.jpg,.jpeg,.png" id="fileToUpload">
  <br>
  <input type="submit" style="display:none; visibility: hidden;" value="If this is visible, report an error to 
[insert email here]" id="submitbtn" name="submit">
  <br>
  <br>
</form>



</div>
<script type="text/javascript">
  VANTA.TRUNK({
    el: "#vanta",
    mouseControls: true,
    touchControls: true,
    gyroControls: false,
    minHeight: 200.00,
    minWidth: 200.00,
    scale: 1.00,
    scaleMobile: 1.00,
    color: "#0072c5",
    backgroundColor: "#2b2b2b",
    spacing: 8.00,
    chaos: 3.50
  })
</script>
<script>
  function selectfile(){
    document.getElementById('fileToUpload').click();
  }
  function upload(){
    document.getElementById('submitbtn').click();
  }
</script>
</body>
</html>

I'm not sure what I did wrong, any assistance would be helpful. Some information has been removed due to it being personal data Thanks

PHP 5.4.9 and nginx 1.14.0



Solution 1:[1]

Use a <label> instead of using JavaScript, and associate it with your <input> element.

<label>

<label for="fileToUpload"><img class="centered" style="cursor: pointer;" src="https://media.discordapp.net/attachments/906303123419693066/961061738512515082/Untitled_drawing_2.png" width="100px"></label>

<input>

<input type="file" name="fileToUpload" accept=".gif,.jpg,.jpeg,.png" id="fileToUpload">

Also, update your PHP version because 5.4.9 is very outdated. I recommend version 7 or higher.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rocord01