How to limit or limit html tags that a user can enter into a web form, pref. client side?

What are the good options for restricting the type of html tags that a user is allowed to enter a form field? I would like to be able to do this client side (presumably using JavaScript), the server side in PHP, if it is too heavy for the user's browser, and possibly a combination of both, if necessary.

In fact, I would like users to be able to send data with the same set of tags as in Stackoverflow, plus possibly standard MathML tags. The form should take the text UTF-8, including Asian ideograms, etc.

In the application, the user should be able to send text entries with basic html tags, and these entries should be accessible to (potentially different) users with html displayed in a way that is safe for users. I plan to use htmlspecialchars()it htmlspecialchars_decode()to protect my server side of the server.

Many thanks,

Jdelage

PS: I searched, but could not find this question ...

+3
source share
4 answers

If you want to filter your input again with XSS attacks, etc., consider using an existing library such as HTML Purifier . I have not used it myself yet, but it promises a lot and is very appreciated.

HTML- - -    HTML-,   PHP. HTML    ( XSS) ,   , ,    ,    ,    W3C.

+3
+1

- , :

<?php

function parse($string)
{
//To stop unwanted HTML tags being used
$string = str_replace("<","&lt;",$string); //Replace all < with the HTML equiv
$string = str_replace(">","&gt;",$string); //Replace all > with the HTML equiv

$find = array(
"%\*\*\*(.+?)\*\*\*%s", //Search for ***any string here***
"%`(.+?)`%s",           //Search for `any string here`
);

$replace = array(
"<b>\\1</b>",                                          //Replace with <b>any string here</b>
"<span style=\"background-color: #DDDDDD\">\\1</span>" //Replace with <span style="background-color: #DDDDDD">any string here</span>
);

$string = preg_replace($find,$replace,$string); //Do the find and replace
return $string; //Return the output
}

echo parse("***Hello*** `There` <b>Friend</b>");
?>

:

There <b> </b>

0

I had a similar problem for some time. There were some $% ^ & *) who liked to post comments like <script>alert('Hello');</script>or something like that. I was tired and made a small function that helped me only allow tags <br>or <br />for normal viewing of the message. I only did this in PHP, but I think it can help you.

function eliminateTags($msg) {
    $setBrakes = nl2br($msg);
    $decodeHTML = htmlspecialchars_decode($setBrakes);

    # Check PHP version
    if(version_compare(PHP_VERSION, '5.2') == 1) {
        $withoutTags = strip_tags($decodeHTML, "<br />");
    } else {
        $withoutTags = strip_tags($decodeHTML, "<br>");
    }
    return $withoutTags;
}
0
source

Source: https://habr.com/ru/post/1750905/


All Articles