简体   繁体   中英

Stop html in text entered

hello all I realise this is something that comes up a lot and I have looked at loads of different posts and answers to try and find out my own answer before bothering to post on here, however I am really struggling to get the following to work.

I am in the process of making a chat room, if you type text into the text box then click the enter key id of 30 then the message is sent (this is the normal function). However, if you are to type html into the text box then the html will take place when the message is sent. This is causing great issues in the progression of my project. There are many posts out there saying use...

htmlspecialchars();

I am finding before the messages even reaches my PHP file the html entered in the text box has already taken place on the enter key being clicked. I'm now trying to find something which I can do in the javascript section where I can stop text as it is being entered and make adjustments to the text box so if I was to enter the following key ....

<   //which has the key ID of 60

It would then replace it in the text box to be /< or even constantly checking and replacing html chars in the text box when the key down function takes place and then replaces them. This would mean when I then take the text out of the text box it would already be decoded and no html tags will be in the message, which would then stop them taking effect on my chat room.

Something such as the following code...

$("#messagearea").keydown(function{
    var replacementtext = this.replace() // html characters I'm not that familiar with        this function but I believe it is what I need to use.
    messagearea = replacementtext
}

Something like the above would then allow me to check the characters entered each time there was a key down event and stop html from being messed with on my site. If anyone could give me some help on how this should be written or if there is a better way of doing this? That would be great many thanks.

Your problem is so common that the great guys from jQuery already solved it for you.

var encodedText = $("#message-box").text();

Have a look at the jQuery documentation for an in-depth discussion of the text function.


Okay, let me extend my answer because of Dave's comments. Ultra basic example on how to achieve what I think Dave meant.

Your HTML:

<!doctype html>
<html>
<head>
  <title>Chat</title>
  <style>.invalid{border:red}</style>
</head>
<body>
  <div id="chat">
    <p><span class="user">Foo:</span> Bar</p>
  </div>
  <form id="message-form" action="/chat.php" method="post">
    <textarea id="message" name="message" placeholder="Enter chat message ..." autofocus></textarea>
    <input type="submit" value="Send">
  </form>

Your jQuery:

$(function () {
  var $chat = $('#chat');
  var $messageForm = $('#message-form');
  $messageForm.$message = $('#message');
  $('#message-form').submit(function (e) {
    e.preventDefault();
    this.originalMessage = this.$message.val();
    this.$message.val('').prop('disabled', true);
    $.post('/chat.php', { json: true, message: this.originalMessage }, function (response) {
      if (response.error) {
        $messageForm.$message
          .val($messageForm.originalMessage)
          .addClass('invalid')
        ;
      }
      else {
        $chat.append('<p><span class="user">' + response.name + ':</span> ' + response.message + '</p>');
      }
      $messageForm.$message.prop('disabled', false).focus();
    }, 'json');
  });
});

Your PHP:

<?php

$json = filter_input(INPUT_POST, "json", FILTER_VALIDATE_BOOLEAN);

if (($message = filter_input(INPUT_POST, "message", FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_REQUIRE_SCALAR)) !== false) {
  session_start();
  $return = [
    "name" => $_SESSION["name"],
    "message" => htmlspecialchars($message, ENT_QUOTES|ENT_HTML5),
  ];
}
else {
  $return = [ "error" => true ];
}

if ($json === true) {
  header("content-type: application/json");
  exit(json_encode($return));
}

var_dump($return);

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM