What are the potential security risks when not filtering user input in PHP image file handling?

When not filtering user input in PHP image file handling, there is a risk of allowing malicious files to be uploaded to the server, which can lead to security vulnerabilities such as code execution or unauthorized access to sensitive information. To mitigate this risk, it is important to validate and sanitize user input before processing image uploads.

// Example of filtering user input in PHP image file handling
$allowed_extensions = array('jpg', 'jpeg', 'png');
$upload_folder = 'uploads/';

if(isset($_FILES['image'])){
    $file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    
    if(in_array($file_extension, $allowed_extensions)){
        move_uploaded_file($_FILES['image']['tmp_name'], $upload_folder . $_FILES['image']['name']);
        echo 'Image uploaded successfully!';
    } else {
        echo 'Invalid file type. Only JPG, JPEG, and PNG files are allowed.';
    }
}