Reputation: 2188
I want to replace <
and >
in a php string before inserting into the database so when a user types a code, it won't execute its function so I did this:
$comment = str_replace("<", "<", $comment);
$comment = str_replace(">", ">", $comment);
But I also have something like this within the string <3msg
which I don't want to replace Please How do I run my code.
Upvotes: 0
Views: 57
Reputation: 870
See Here.
you can use htmlentities() to achieve your output.
$str = "A 'quote' is <b>and</b>";
// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str);
// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str, ENT_QUOTES);
PS
to see result, see view source you it will look a like this.
Upvotes: 0
Reputation: 2985
If you want to sanitize database input to remove scripts etc then you can use strip_tags
like this:
$comment = strip_tags($comment)
Alternatively if you want to keep tags but not allow code injection then you can also use htmlspecialchars
which will make a more thorough and comprehensive conversion to ensure you don't miss anything.
Upvotes: 0
Reputation: 2941
If you have one character at different places you need to be more specifi, for example chars which are always next to this or something else. Otherwise you are out of luck since you have to exactly identify the char(s) which you want to replace. For the scenario aboce there is a function called htmlspecialchars (Link)
If you want to be sure that nothing interferes with your query and no sql injection attacks can occur I suggest that you used prepared statements as often as you can. You can read mor about this here and if this is not enough I can give you examples for this.
Upvotes: 0
Reputation: 2655
Use like this
$comment = str_replace("<", "<", $comment);
$comment = str_replace(">", ">", $comment);
$comment = str_replace("<3msg", "<3msg", $comment);
Upvotes: 1