Are there any best practices or recommended methods for handling image uploads in PHP contact forms?

When handling image uploads in PHP contact forms, it is important to validate the file type, size, and ensure secure storage. One recommended method is to use the move_uploaded_file function to move the uploaded file to a designated directory on the server. Additionally, consider renaming the file to avoid any potential conflicts or security risks.

<?php

// Check if file was uploaded without errors
if(isset($_FILES["image"]) && $_FILES["image"]["error"] == 0){
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);
    
    // Check file size
    if($_FILES["image"]["size"] > 500000){
        echo "Sorry, your file is too large.";
    } else {
        // Allow only certain file formats
        $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
        $file_extension = pathinfo($target_file, PATHINFO_EXTENSION);
        
        if(in_array($file_extension, $allowed_types)){
            // Move the uploaded file to the designated directory
            if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)){
                echo "The file ". htmlspecialchars( basename( $_FILES["image"]["name"])). " has been uploaded.";
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        } else {
            echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        }
    }
} else {
    echo "No file uploaded or an error occurred.";
}

?>