PHP AJAX聊天 - 聊天命令逻辑?

I've been developing a PHP ajax chat. I now want to add commands like /ban and so on.

But I am not sure how would I do that.

In the first place, I want the commands to start with a '/' sign.

Do I have to first check if the sent message is starting with a '/' sign, correct? And then see if the command 'ban' exists, but how will it know, where in the sentence, the username will be displayed in?

I am really confused, as I have no idea where and how to start. Is there a open source of commands system similar to my needs?

You need to define a syntax for your commands yourself. For example /ban <username> for a ban.

  1. First you check whether the message begins with a slash. If so it is a command.
  2. Now search for the first space, everything after the slash and in front of the space is the command name.
  3. Pass everything after the first space to the command. In this case the username. The command handles the parameters on it's own.

It could look like this:

$message = '/ban TimWolla';
if (substr($message, 0, 1) === '/') {
    // $message is a command
    $firstSpace = strpos($message, ' ');
    $command = substr($message, 1, $firstSpace);
    $parameters = substr($message, $firstSpace + 1);

    if (!hasPermission($command)) error('Permission denied');

    switch ($command) {
        case 'ban':
            ban($parameters);
        break;
    }
} 

In case you want to use proper OOP make each command a class and use an interface for all commands to require the proper methods. e.g.:

interface Command {
    public function setParameters($parameters);
    public function hasPermission();
    public function execute();
}

All messages should be sent to the server.

I.e if the message is "Hello, welcome to the channel" - this should be interpreted as a MSG command on the server.

You should have a Command parser server side to deal with the type of message. For instance, if a MSG message gets passed up, send it to the MessageParser. If a / command is passed up send it to the CommandParser.

A ban command should be in the form of:

/ban username

At the server side level you should check that the user trying to perform the command is an operator, if he/she is then lookup the username's IP address and add it to the blacklist on the server.