How can a PHP chat server be implemented with data stored in CSV files instead of a database?

To implement a PHP chat server with data stored in CSV files instead of a database, you can use PHP's file handling functions to read and write messages to a CSV file. Each row in the CSV file can represent a message with columns for the sender, recipient, timestamp, and message content. By using CSV files, you can store chat data without the need for a database server.

// Function to save a new message to the CSV file
function saveMessage($sender, $recipient, $message) {
    $data = [$sender, $recipient, date('Y-m-d H:i:s'), $message];
    $file = fopen('chat_data.csv', 'a');
    fputcsv($file, $data);
    fclose($file);
}

// Function to retrieve all messages from the CSV file
function getMessages() {
    $messages = [];
    $file = fopen('chat_data.csv', 'r');
    while (($data = fgetcsv($file)) !== false) {
        $messages[] = $data;
    }
    fclose($file);
    return $messages;
}

// Example usage
saveMessage('Alice', 'Bob', 'Hello, Bob!');
saveMessage('Bob', 'Alice', 'Hi, Alice!');
$allMessages = getMessages();
foreach ($allMessages as $message) {
    echo "{$message[0]} said to {$message[1]} at {$message[2]}: {$message[3]}\n";
}