Are there any best practices or recommendations for allowing users to upload files through a form on a website?

When allowing users to upload files through a form on a website, it is important to validate the file type, size, and ensure proper security measures are in place to prevent malicious files from being uploaded. One best practice is to use server-side validation to check the file type and size before processing the upload.

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

    // Check file type
    $allowed_types = array('jpg', 'jpeg', 'png', 'pdf');
    $file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    if(!in_array($file_ext, $allowed_types)){
        die('Invalid file type. Allowed types: jpg, jpeg, png, pdf');
    }

    // Check file size
    $max_size = 5 * 1024 * 1024; // 5MB
    if($file['size'] > $max_size){
        die('File is too large. Max size: 5MB');
    }

    // Move the file to a permanent location
    $upload_dir = 'uploads/';
    $upload_file = $upload_dir . $file['name'];
    if(move_uploaded_file($file['tmp_name'], $upload_file)){
        echo 'File uploaded successfully!';
    } else {
        echo 'Error uploading file.';
    }
}
?>