What are the best practices for handling file uploads in PHP to prevent possible security vulnerabilities, such as file upload attacks?

File upload attacks are a common security vulnerability in PHP applications. To prevent such attacks, it is important to validate and sanitize the file uploads before storing them on the server. This can be done by checking the file type, limiting the file size, and storing the files in a secure directory outside of the web root.

<?php

// Check if a file was uploaded
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];

    // Check file type
    $allowedTypes = ['image/jpeg', 'image/png'];
    if(!in_array($file['type'], $allowedTypes)) {
        die('Invalid file type.');
    }

    // Limit file size
    if($file['size'] > 1000000) {
        die('File is too large.');
    }

    // Store file in a secure directory
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($file['name']);
    if(move_uploaded_file($file['tmp_name'], $uploadFile)) {
        echo 'File uploaded successfully.';
    } else {
        echo 'Error uploading file.';
    }
}

?>