<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP File Upload</title>
</head>
<body>
    <form action="index.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>




<?php
$currentDirectory = getcwd();
$uploadDirectory = "/"; //Use /uploads/ when uploader file is in root dir.
$errors= [];


$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'])) {


//CHECK IF FILE IS ALLOWED
$allowed= "/jpg|png|.+/";
if(!preg_match($allowed, $fileExtension)){
$errors[]= "This file extension is not allowed";
}

//CHECK IF FILE ISN'T TOO BIG
if ($fileSize > 4000000){
$errors[]= "File exceeds maximum size (4MB)";
}


//IF NO ERRORS
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.";
}

}

//There were errors; [error] not empty!!
else {
foreach($errors as $error){
echo $error . "\n";
}
}


}
?>