Avoid code injection but allow script tag

Hi everyone,

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:

function evitamos_script($texto) {

    $limpia = strip_tags($texto, '<b> <i> <u> <quote> <img> <center> <cite> <a> <div> <a> <blockquote> <script>'); //EVITAMOS SCRIPTS

    return $limpia;
}

Works fine but I would like to let users share tuits for example, but as embed tuits use scripts I don’t know how solve this problem.

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.

Thanks for your response. I have tried but It shows me the text only. I mean, is safe but the embed tuit is not shown, only html text.

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>&lt;script&gt; function nastyScript() { /* The code */ } &lt;/script&gt;</code>

Which is safe, but will display on-page like:-

<script> function nastyScript() { /* The code */ } </script>	

As it were written.

1 Like

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:-

<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

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.

2 Likes

That’s it sorry. I don’t know how to make it run.

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

2 Likes

Thanks, but is using JSON, I don’t know how to make it work. Do I have to put the code inside <script> tags?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.