bodovix
bodovix

Reputation: 349

how to stop user putting HTML code in text inputs

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?

Upvotes: 2

Views: 163

Answers (3)

VoteyDisciple
VoteyDisciple

Reputation: 37793

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.)

Upvotes: 5

David Ferenczy Rogožan
David Ferenczy Rogožan

Reputation: 25381

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']);

Upvotes: 2

nikoskip
nikoskip

Reputation: 1920

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 "\n";

// Allows <p> and <a>
echo strip_tags($text, '<p><a>'); // Output: <p>Test paragraph.</p> <a href="#fragment">Other text</a>
?>

Upvotes: 4

Related Questions