Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rescrict a JavaScript script being inserted in the database with PHP?

I have one problem regarding the data insertion in PHP.

In my site there is a message system.

So when my inbox loads it gives one JavaScript alert.

I have searched a lot in my site and finally I found that someone have send me a message with the text below.

<script>
  alert(5)
</script>

So how can I restrict the script code being inserted in my database?

I am running on PHP.

like image 810
Avinash Avatar asked Feb 26 '26 00:02

Avinash


2 Answers

There is no problem with JavaScript code being stored in the database. The actual problem is with non-HTML content being taken from the database and displayed to the user as if it were HTML. The correct approach would be to make sure your rendering code treats text as text, not as HTML.

In PHP, this would be done by calling htmlspecialchars on the inbox contents when displaying the inbox (possibly along with nl2br and maybe turning links to <a> tags).

Avoid using striptags for text content: as an user, I might want to type a message like:

... and to create a link, use <a href="your-url-here">your-text-here</a> ...

striptags would eliminate the tag, htmlspecialchars would make the text appear as it was typed.

like image 142
Victor Nicollet Avatar answered Feb 27 '26 13:02

Victor Nicollet


You should not restrict it to be inserted into the database (if StackOverflow would restrict it, we would not be able to post code examples here!)

You should better control how you display it. For instance, add htmlentities() or htmlspecialchars() to your echo call.

like image 44
naivists Avatar answered Feb 27 '26 12:02

naivists