如何阻止用户将HTML代码放入文本输入中
iv been building a website and while testing I noticed that if I put <em>bob</em>
or something similar in my text fields on my register/udate pages they are stored on the database as entered '<em>bob</em>'
but when called back on to the website they display in italics
is there a way to block html code from my text inputs? or dose it only read as html when being echoed back on the page from the database? mostly just curious to know what's happening here? the name displaying in italics isn't a major issue but seems like something the user shouldn't be able to control?
p.s. i can provide code if needed but didn't think it would be much help in this question?
iv正在建立一个网站,在测试时我发现如果我把 或在我的注册/ udate页面上的文本字段中类似的东西,它们存储在数据库中,如输入 有没有办法阻止我的文本输入中的HTML代码?\也不会只是将其读作html 当从数据库回显到页面上时?
只是好奇地想知道这里发生了什么?
用斜体显示的名称不是主要问题,但似乎是用户无法控制的东西? p >
PS 如果需要,我可以提供代码,但不认为这个问题会有多大帮助? p>
div>&lt; em&gt; bob&lt; / em> code> p>
'&lt; em&gt; bob&lt; / em&gt ;' code>但是当回到网站上时,它们以斜体显示 p>
You can use strip_tags
to remove all HTML tags from a string: http://php.net/manual/es/function.strip-tags.php
<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text); // Output: Test paragraph. Other text
echo "
";
// Allows <p> and <a>
echo strip_tags($text, '<p><a>'); // Output: <p>Test paragraph.</p> <a href="#fragment">Other text</a>
?>
You can use builtin PHP function strip_tags
. It will remove all HTML tags from a string and return the result.
Something like that:
$cleaned_string = strip_tags($_GET['field']);
You can also just use htmlspecialchars()
to output exactly what they typed on the page — as-is.
So if they enter <i>bob</i>
then what will show up on the page is literally <i>bob</i>
— that way you're "allowing" all the input in the world, but none of it is ever rendered.
If you want to just get rid of the tags, strip_tags()
is the better option, so <i>bob</i>
would show up as bob
. This works if you're sure there's no legitimate scenario where someone would want to enter an HTML tag. (For example, Stack Overflow obviously can't just strip the tags out of stuff we type, since a lot of questions involve typing HTML tags.)