What are some best practices for designing and implementing a private messaging system in PHP to ensure scalability and security?

Issue: When designing and implementing a private messaging system in PHP, it is important to ensure scalability and security. This can be achieved by properly structuring the database schema, implementing user authentication and authorization, and using secure communication protocols. Code snippet:

// Database schema for private messaging system
CREATE TABLE messages (
    id INT PRIMARY KEY AUTO_INCREMENT,
    sender_id INT,
    receiver_id INT,
    message TEXT,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

// User authentication and authorization
session_start();

if(!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Secure communication protocols
$message = $_POST['message'];
$message = htmlspecialchars($message);
$message = mysqli_real_escape_string($connection, $message);

// Insert message into database
$query = "INSERT INTO messages (sender_id, receiver_id, message) VALUES ('".$_SESSION['user_id']."', '".$_POST['receiver_id']."', '$message')";
mysqli_query($connection, $query);