Reputation: 61
Please let me know how to allow less than character '<' in strip_tags()
Code Snippet
$string ="abc<123";
StringFromUser($string);
function StringFromUser($string)
{
if (is_string($string))
{
return strip_tags($string);
}
}
Output : abc
Expected output abc<123
Upvotes: 5
Views: 3753
Reputation: 5670
The problem: The purpose to use trip_tags is to prevent attacking from HTML or PHP injection. However, trip_tags not only removes HTML and PHP tags, it also removes part of a math expression with a < operator. So, what we see is "abc<123" being replaced to "abc".
The solution: What we know is a < followed by a space is not identified as HTML or PHP tags by strip_tags. So what I do is to replace "abc<123" to "abc< myUniqueID123". Please note there is a space followed the < sign. And also, only numbers followed the < sign are replaced. Next, strip_tags the string. Finally, replace "abc< myUniqueID123" back to "abc<123".
$string = "abc<123";
echo StringFromUser($string);
function StringFromUser($string)
{
if (is_string($string)) {
//change "abc<123" to "abc< myUniqueID123", so math expressions are not stripped.
//use myQuniqueID to identity what we have changed later.
$string = preg_replace("/(<)(\d)/", "$1 myUniqueID$2", $string);
$string = strip_tags($string);
//change "abc< myUniqueID123" back to "abc<123"
$string = preg_replace("/(<) myUniqueID(\d)/", "$1$2", $string);
return $string;
}
}
Upvotes: 0
Reputation: 683
You could search for a character in your string, take it out, strip_tags() your string and put the character back in:
$string = "abc<123";
$character = "<";
$pos = strpos($string,$character);
$tag = ">";
$check = strpos($string,$tag);
if ($pos !== false && $check == false) {
$string_array = explode("<",$string);
$string = $string_array[0];
$string .= $string_array[1];
$string = strip_tags($string);
$length = strlen($string);
$substr = substr($string, 0, $pos);
$substr .= "<";
$substr .= substr($string, $pos, $length);
$string = $substr;
} else {
$string = strip_tags($string);
}
or you could use preg_replace() to replace all the characters you don't want to have in your $string.
Upvotes: 0
Reputation: 522032
strip_tags
is a pretty basic and not very good way to sanitize data (i.e. "punch arbitrary values into shape"). Again, it's not a very good function, as you are seeing. You should only sanitize data if you have a very good reason to, oftentimes there is no good reason. Ask yourself what you are gaining from arbitrarily stripping out parts of a value.
You either want to validate or escape to avoid syntax problems and/or injection attacks. Sanitization is rarely the right thing to do. Read The Great Escapism (Or: What You Need To Know To Work With Text Within Text) for more background on the whole topic.
Upvotes: 1
Reputation: 798576
Encode it properly in the first place.
$string ="abc<123";
Although if you're not sanitizing for HTML output you shouldn't be using strip_tags()
anyway.
Upvotes: 1