Wednesday, March 31, 2021

Configure File uploads server on localhost

Step 1) Install webserver

$ sudo apt-get install apache2 -y

Step 2) Make a directory under /var/www/html/

$ sudo mkdir /var/www/html/sharedoc/
$ sudo mkdir /var/www/html/sharedoc/uploads

Step 3) Add below following content in /var/www/html/sharedoc/fileUploadScript.php

$ sudo vim /var/www/html/sharedoc/fileUploadScript.php

<?php
    $currentDirectory = getcwd();
    $uploadDirectory = "/uploads/";

    $errors = []; // Store errors here

    $fileExtensionsAllowed = ['sql','jpeg','pdf','jpg','png','exe','dmg','tar.gz','gz','zip']; // These will be the only file extensions allowed

    $fileName = $_FILES['the_file']['name'];
    $fileSize = $_FILES['the_file']['size'];
    $fileTmpName  = $_FILES['the_file']['tmp_name'];
    $fileType = $_FILES['the_file']['type'];
    $fileExtension = strtolower(end(explode('.',$fileName)));

    $uploadPath = $currentDirectory . $uploadDirectory . basename($fileName);

    if (isset($_POST['submit'])) {

      if (! in_array($fileExtension,$fileExtensionsAllowed)) {
        $errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
      }

      if ($fileSize < 1024) {
        $errors[] = "File exceeds maximum size (4MB)";
      }

      if (empty($errors)) {
        $didUpload = move_uploaded_file($fileTmpName, $uploadPath);

        if ($didUpload) {
          echo "The file " . basename($fileName) . " has been uploaded";
        } else {
          echo "An error occurred. Please contact the administrator.";
        }
      } else {
        foreach ($errors as $error) {
          echo $error . "These are the errors" . "\n";
        }
      }

    }
?>

Step 4) Add below following content in  /var/www/html/sharedoc/index.html

$ sudo vim /var/www/html/sharedoc/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload</title>
</head>
<body>
    <form action="fileUploadScript.php" method="post" enctype="multipart/form-data">
        Upload a File:
        <input type="file" name="the_file" id="fileToUpload">
        <input type="submit" name="submit" value="Start Upload">
    </form>
</body>
</html>


Step 5) Type localhost/sharedoc in browser and add any file.

Step 6) Check uploaded files in /var/www/html/sharedoc/uploads/

$ ls /var/www/html/sharedoc/uploads/



No comments:

Post a Comment

testing