0

I have my website project where users can comment on posts. I want to allow users to submit YouTube videos for example. I want to display them in an iframe so others see a nice window of the video.

But that means that users can exploit the website using all the HTML tags and scripts?

put something like that
< a href="">< script>alert();< /script>">
which would break the site...

What ways do I have around that?

I want to make sure the user cannot use any tags.. but when link is posted it wraps it in the iframe.

One way I thought of is just to put separate input window only for urls which will be wrapped in iframe. but that complicates everything. I would also like to stick with one comment window.

Any suggestions?

Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152
mrHarry
  • 13
  • 3
  • Possible duplicate of [How to prevent XSS with HTML/PHP?](https://stackoverflow.com/questions/1996122/how-to-prevent-xss-with-html-php) – Obsidian Age Nov 28 '17 at 23:11
  • You're asking how to prevent XSS. For that, you need to sanitize the input on the server. The above link shows how to do that in PHP, and [**this question**](https://stackoverflow.com/questions/71328/what-are-the-best-practices-for-avoiding-xss-attacks-in-a-php-site) discusses some of the best practices in general. – Obsidian Age Nov 28 '17 at 23:11
  • 3
    Don't let them provided HTML. Simply parse their text for a YouTube URL. Then perform a replace which inserts the `iframe` and uses the provided URL. – hungerstar Nov 28 '17 at 23:12

1 Answers1

0
  1. Don't let users enter HTML.
  2. Parse user comment for YouTube URL.
  3. Replace URL with <iframe> pointing to provided URL.

Here is a super simple JavaScript example to work from.

https://jsfiddle.net/ntgs3ypt/

var comment = document.querySelector('textarea');
var output = document.querySelector('div');

var str = comment.value;
var regex = /(https:\/\/www.youtube.com\/embed\/\w*)/;

if (regex.test(str)) {

  str = str.replace(regex, '<iframe width="560" height="315" src="$1" frameborder="0" allowfullscreen></iframe>');
  output.innerHTML = str;

}
textarea {
  width: 100%;
}
<textarea name="comment">Lorem ipsum dolor https://www.youtube.com/embed/mr7FXvTSYpA lorem ipsum dolor</textarea>

<div class="output"></div>
hungerstar
  • 21,206
  • 6
  • 50
  • 59