What are some best practices for ensuring the security of a messenger with file exchange feature on a website using PHP?

To ensure the security of a messenger with file exchange feature on a website using PHP, it is important to validate and sanitize user input to prevent SQL injection and cross-site scripting attacks. Additionally, file uploads should be restricted to certain file types and sizes to prevent malicious files from being uploaded. It is also recommended to store uploaded files outside of the web root directory to prevent direct access.

// Validate and sanitize user input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);

// Restrict file uploads to certain types and sizes
$allowed_file_types = array('jpg', 'jpeg', 'png', 'pdf');
$max_file_size = 5 * 1024 * 1024; // 5MB

if ($_FILES['file']['size'] > $max_file_size || !in_array(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION), $allowed_file_types)) {
    // Handle error for invalid file type or size
}

// Store uploaded files outside of the web root directory
$upload_dir = '/path/to/uploaded/files/';
$upload_file = $upload_dir . basename($_FILES['file']['name']);

if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
    // File uploaded successfully
} else {
    // Handle error for failed file upload
}