Secure File Uploading With PHP



The code used for index.php is below:


<!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">
    <link rel="stylesheet" href="styles.css">
    <title>Secure File Uploading With PHP</title>
</head>
<body>

<h1>Secure File Uploading With PHP</h1>

<form action="" method="POST" enctype="multipart/form-data">
    <label for="image">
    <input type="file" name="image">
    </label>
        <input type="submit" value="Upload">
</form>
<hr>
<?php

// move_uploaded_file

if(isset($_FILES['image'])){

    $errors = [];
    $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];

    $file_name = $_FILES['image']['name'];
    $file_ext = strtolower(end(explode('.', $file_name))); //end() grabs last element in array which is the file extension

    $file_size = $_FILES['image']['size'];
    $file_tmp = $_FILES['image']['tmp_name'];

    if (in_array($file_ext, $allowed_ext) === false){
        $errors[] = 'File Type Not Allowed.';
    }

    if($file_size > 2100000){
        $errors[] = 'File Size Must Be Under 2 Megabytes';
    }

    if(empty($errors)){
        //upload file
        if(move_uploaded_file($file_tmp, 'images/'.$file_name)){
            echo "<h2>File Uploaded!</h2>";
            echo "<img src='images/$file_name'>";
        };

    } else {
        foreach($errors as $error){
            echo "<h3>$error</h3>";
        }
    }
}

?>

<?php
    include('../show_code.php');
    show_code('index.php');
?>


</body>
</html>