How can PHP be used to handle file uploads and validate file formats?

To handle file uploads and validate file formats in PHP, you can use the $_FILES superglobal array to access the uploaded file data. You can then use functions like pathinfo() to get the file extension and check if it matches the allowed file formats. Additionally, you can use functions like move_uploaded_file() to save the uploaded file to a specific directory.

<?php
$uploadDir = 'uploads/';
$allowedFormats = ['jpg', 'png', 'gif'];

if(isset($_FILES['file'])){
    $file = $_FILES['file'];
    $fileName = $file['name'];
    $fileTmpName = $file['tmp_name'];
    $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);

    if(in_array($fileExt, $allowedFormats)){
        $destination = $uploadDir . $fileName;
        if(move_uploaded_file($fileTmpName, $destination)){
            echo "File uploaded successfully!";
        } else {
            echo "Failed to upload file.";
        }
    } else {
        echo "Invalid file format. Allowed formats: " . implode(', ', $allowedFormats);
    }
}
?>