How can PHP be used to implement a whisper chat feature where users can send private messages to each other?

To implement a whisper chat feature in PHP, you can create a messaging system where users can send private messages to each other by specifying the recipient. This can be achieved by storing messages in a database with fields for sender, recipient, message content, and timestamp. When a user sends a message, the PHP script should check if the recipient exists and then insert the message into the database.

// Assuming you have a database connection established

// Code to handle sending a whisper message
if(isset($_POST['recipient']) && isset($_POST['message'])) {
    $sender = $_SESSION['user_id']; // Assuming user is logged in
    $recipient = $_POST['recipient'];
    $message = $_POST['message'];
    
    // Check if recipient exists
    $check_recipient_query = "SELECT * FROM users WHERE id = $recipient";
    $check_recipient_result = mysqli_query($conn, $check_recipient_query);
    
    if(mysqli_num_rows($check_recipient_result) > 0) {
        // Insert message into database
        $insert_message_query = "INSERT INTO messages (sender_id, recipient_id, message, timestamp) VALUES ($sender, $recipient, '$message', NOW())";
        mysqli_query($conn, $insert_message_query);
        echo "Message sent successfully!";
    } else {
        echo "Recipient does not exist.";
    }
}