What are common pitfalls when trying to upload and save an avatar using PHP?

Common pitfalls when trying to upload and save an avatar using PHP include not properly setting the enctype attribute in the form tag, not checking the file type and size before uploading, and not securing the uploaded file against potential security risks. To solve these issues, make sure to set the form enctype attribute to "multipart/form-data", validate the file type and size before uploading, and move the uploaded file to a secure directory on the server.

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    if(isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0){
        $file_name = $_FILES['avatar']['name'];
        $file_size = $_FILES['avatar']['size'];
        $file_tmp = $_FILES['avatar']['tmp_name'];
        
        $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
        $allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
        
        if(in_array($file_ext, $allowed_ext) && $file_size < 1048576){
            $upload_dir = 'uploads/';
            $new_file_name = uniqid() . '.' . $file_ext;
            
            if(move_uploaded_file($file_tmp, $upload_dir . $new_file_name)){
                echo 'Avatar uploaded successfully.';
            } else {
                echo 'Failed to upload avatar.';
            }
        } else {
            echo 'Invalid file type or size. Please upload a file under 1MB in jpg, jpeg, png, or gif format.';
        }
    } else {
        echo 'Error uploading file.';
    }
}
?>