What are some best practices for handling file uploads in PHP, considering security and user input validation?

When handling file uploads in PHP, it is crucial to validate user input to prevent malicious uploads and ensure security. One best practice is to check the file type and size before allowing the upload. Additionally, it is recommended to store uploaded files outside of the web root directory to prevent direct access.

// Check if the file was uploaded without errors
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    // Validate file type
    $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
    if (!in_array($_FILES['file']['type'], $allowedTypes)) {
        echo 'Invalid file type.';
        exit;
    }

    // Validate file size
    if ($_FILES['file']['size'] > 5242880) { // 5MB
        echo 'File is too large.';
        exit;
    }

    // Move the uploaded file to a secure location
    move_uploaded_file($_FILES['file']['tmp_name'], '/path/to/uploads/' . $_FILES['file']['name']);
} else {
    echo 'Error uploading file.';
}