Reputation: 26565
I need a way:
to lets users to use ONLY <strong>
and <p>
tags.
to avoid users to use CSS with these tags ( for example this must NOT works: <p style="margin:1000px;"> hello </p>
).
to avoid XSS.
htmlspecialchars
is not sufficient because it convert all tags in html entities.
strip_tag
is not sufficient because it allow CSS in the tags.
So what PHP functions can I use to do this ?
I don't want to use an external library like html purifier.
Upvotes: 2
Views: 439
Reputation: 701
The Web adopted solutions like MarkDown Language, exactly for these purposes.
Maybe you should implement a Markdown Editor on the client side and a Markdown decoder on the server side. It will permit your users to format their texts but block them, at the XSS / CSS point of view.
http://daringfireball.net/projects/markdown/
K.
Upvotes: 0
Reputation: 655707
You could write your own little lexer and parser for this very limited subset of HTML:
$input = '…';
$tokens = preg_split('~(</?(?:p|strong)\s*>)~', $input, -1, PREG_SPLIT_DELIM_CAPTURE);
var_dump($tokens);
foreach ($tokens as $i => &$token) {
if ($i % 2 === 0) {
// text
$token = htmlspecialchars($token);
} else {
// tag
}
}
$output = implode('', $tokens);
Upvotes: 2
Reputation: 3496
The best idea I can think (within the boundaries you require) is to use a custom string of text for <p>
and <strong>
and then str_replace
it with the HTML tags on output. This way they can't inject anything dodgy.
You see this on a lot of forum websites when writing a post, where the user's can click paragraph and bold icons and it will put [p][/p]
instead of <p></p>
. Then on output str_replace [p]
with <p>
and [/p]
with </p>
. If they put any custom CSS or scripts in, then the string_replace
would fail and not output any HTML that the browser would render.
Upvotes: 2