How can one ensure the security and efficiency of an image upload feature in PHP?

To ensure the security and efficiency of an image upload feature in PHP, it is important to validate the uploaded file, restrict file types to only allow images, and save the uploaded images in a secure directory on the server.

// Validate the uploaded file
if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
    // Check if the file is an image
    $fileType = exif_imagetype($_FILES['image']['tmp_name']);
    if ($fileType !== false) {
        // Save the uploaded image in a secure directory
        move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/' . $_FILES['image']['name']);
        echo 'Image uploaded successfully.';
    } else {
        echo 'Invalid file type. Only images are allowed.';
    }
} else {
    echo 'Error uploading file.';
}