3

I am designing an basic ecommerce application, where I have a form to add product.

There are 2 text fields: product name, and description.

product name is input type="text", description is textarea

As user can input anything (worst case scenario), I want to remove all tags (no matter its PHP, HTML, JS, CSS, anything), so that I get just plain text (w/o any tags)

How can I achieve this? Basically, I need to sanitize string, so any to make it plain text

I-M-JM
  • 15,732
  • 26
  • 77
  • 103

3 Answers3

1

If you just want to rip out all tags from the user input, then you can use the strip_tags() function.

A better option would be to run the user input through HTML Purifier. It's a more complete clean.

AgentConundrum
  • 20,288
  • 6
  • 64
  • 99
  • I'll definitely add that one to my arsenal when "heavy weaponry" is needed - that looks like a great library! – Michael Petrov Aug 21 '11 at 05:59
  • I think if no he needs no HTML tags for text formating then he can just use htmlspecialchars() for the output. An it should be enough. – Karolis Aug 21 '11 at 14:06
  • This keeps ` ` and `"/\r|\n/"` .. see this [link](https://stackoverflow.com/questions/10757671/how-to-remove-line-breaks-no-characters-from-the-string) to remove those.. – Ahmad Yousef Oct 15 '17 at 13:52
1

I would suggest the strip_tags function, perhaps try something like this:

$cleaner_input = trim(strip_tags($input)); // trim is there for good measure

Make sure that you're also handling magic quotes, otherwise actual quote characters can become a problem and get backslashes before them (they are being depreciated but are still relevant in most hosting environments).

Keep in mind that strip_tags will keep text between tags, so would be somewhat of a problem for JavaScript/CSS but at least the browser will render it as pure text. Give a preview to the user that is entering the data and they will see that they messed up.

Hope that helps!

Michael Petrov
  • 2,247
  • 15
  • 15
1

There is an easy way.

For versions of php<5.2.0 when we have to validate or filter user data, we normally use regex and/or complex php functions.
Some of those regex are difficult to understand/remember. So normally most of the coders search in google to collect the correct regex.

For php>=5.2.0 you can use filter_var.

dusoft
  • 11,289
  • 5
  • 38
  • 44
Panos Kalatzantonakis
  • 12,525
  • 8
  • 64
  • 85