Program to upload a file using php.

Here, we will write a program to upload a file using php. We will have two files here, one will be upload.html which will contain an input box and button to select the file and button action will then send a request to upload.php file.

upload.html file

<!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>Document</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="fileToUpload">
        <input type="submit" value="Upload File" name="submit">
      </form>
</body>
</html>

upload.php file

<?php
if(isset($_POST["submit"])) {
    $targetDir = "uploads/"; // directory where uploaded files will be stored
    $targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]); // get the filename
  
    // Check if file already exists
    if (file_exists($targetFile)) {
      echo "Sorry, file already exists.";
    }
  
    // Upload file
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
      echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
    } else {
      echo "Sorry, there was an error uploading your file.";
    }
  }
  
?>