Storing the last input text whilst using the POST method with PHP

83 views Asked by At

The idea:

I have been trying to create a one-way chat system based on predictions from the user, using pre-set automatic responses through the server side.

The problem:

What I have so far works great, although the problem I have now is that I can't store the last user inputted message locally for the chat to flow in messages without using lots of _GET's.

With my current code:

if (isset($_POST['test'])) {
    $test = htmlentities($_POST['test']);
    echo "<span class='you'>".$name."</span>: ".$test;
    if (preg_match('~\b(?:about)\b~', $test)) {
        echo '<br />'.$about;
    } else if (preg_match('~\b(?:projects?|works?)\b~i', $test)) {
        echo '<br />'.$projects;
    } else if (preg_match('~\b(?:contact|email|inquiry)\b~', $test)) {
        echo '<br />'.$contact;
    } else {
        echo "<br />Error!";
    }
}

For example, if the user types projects into the input, $projects echo's correctly, but after if the user types about, $about does show, but the previous projects message disappears.

What I have tried:

  • I've tried to put each if in its own isset.
  • Thought about a loop that makes a new input after every message, although I believe this is probably not efficient use of PHP, I need to find a more minimal way.
1

There are 1 answers

2
Loïc On

You could use so AJAX that old messages won't disappear on submit.

Have an <ul> for the chat messages. When user posts, create a <li> with his message and another one for the answer, and keep adding them...