I have a website were users can post. The problem is that to avoid code injection, I´m not letting some tags, among those, the <script> one. For this purpose I´m using this code:
What do you mean by “tuits”?
If your users are posting code, one way to make it appear on-screen and be safe is to use htmlspecialchars(), it will encode the characters to be safe, but still display as those characters.
I’m not sure what you mean, or what you are trying to do. Can you give a clear example?
What I was suggesting would work like this:-
<?php
$texto = "<script> function nastyScript() { /* The code */ } </script>" ; // If this was the string with malicious (or any) code
?>
<code><?php echo htmlspecialchars($texto) ?></code>
What that outputs is this:-
<code><script> function nastyScript() { /* The code */ } </script></code>
Which is safe, but will display on-page like:-
<script> function nastyScript() { /* The code */ } </script>
OK, I found this out, for the benefit of anyone else, this translates to “Tweets”, as in posts on Twitter.
From what I see the embed code of a tweet consists of a <blockquote> containing <p> and <a> html elements, followed by a <script> element looking like this:-
Assuming that script code is the same for all tweets (the charset may vary for some) it may be possible to search that string and allow only that script to run. Though I don’t have a method for that just now.
It may be better/safer to use an API to convert a Tweet URL into embed code.
See the section “Convert Tweet URLs using oEmbed” here:- https://dev.twitter.com/web/embedded-tweets