What are common methods for image upload and format validation in PHP?

When users upload images to a website, it is important to validate the file format to ensure security and prevent potential vulnerabilities. One common method to validate image uploads in PHP is by checking the file extension and MIME type of the uploaded file against a list of allowed formats. This helps to prevent users from uploading malicious files or files that could potentially harm the server.

// Check if the file is an image and has a valid format
$allowedFormats = ['jpg', 'jpeg', 'png', 'gif'];
$uploadedFile = $_FILES['image']['tmp_name'];
$uploadedFileType = $_FILES['image']['type'];
$uploadedFileName = $_FILES['image']['name'];
$uploadedFileExt = pathinfo($uploadedFileName, PATHINFO_EXTENSION);

if (in_array($uploadedFileExt, $allowedFormats) && exif_imagetype($uploadedFile)) {
    // Process the image upload
    move_uploaded_file($uploadedFile, 'uploads/' . $uploadedFileName);
    echo 'Image uploaded successfully!';
} else {
    echo 'Invalid image format. Please upload a valid image file.';
}