What are some best practices for handling file uploads and form submissions in PHP to ensure reliable delivery of data and files?

When handling file uploads and form submissions in PHP, it is important to validate and sanitize user input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. Additionally, it is crucial to set appropriate file upload limits and handle errors gracefully to ensure reliable delivery of data and files.

<?php
// Validate and sanitize user input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

// Set file upload limits
$maxFileSize = 5 * 1024 * 1024; // 5MB
$allowedFileTypes = ['jpg', 'png', 'gif'];

// Handle file upload
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileSize = $_FILES['file']['size'];
    $fileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

    if ($fileSize <= $maxFileSize && in_array($fileType, $allowedFileTypes)) {
        $uploadPath = 'uploads/' . $_FILES['file']['name'];
        move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath);
        echo 'File uploaded successfully!';
    } else {
        echo 'Invalid file size or type.';
    }
} else {
    echo 'Error uploading file.';
}
?>