Is there a way to somehow sandbox user-generated content? I'm working on webapp which will contain a lot of user-generated content. Only "trusted" users will be able to publish the content, but I want to make sure nothing will go wrong if someone compromises their account. They will be able to upload all kinds of files (except binary executables), all of them will be served directly (e.g. PHP file won't be executed).

Considering the worst-case scenario - someone compromises user's account and uploads malicious HTML file with script, which is e.g. stealing cookies or doing AJAX calls, what's the best way to handle this?

Is it sufficient to move the content to subdomain, like https://usercontent.webappdomain.com

Are there any better ways of preventing these issues?

  • Are you supposed to serve the files directly? Because you could always provide sort of a "view" (sanitized representation) of of the file with an option to download the real file on that page. I forget the site that does that but many do. There was at least one image hosting website that doesn't expose the actual image if you go to hosting.com/imageURL.jpg but actually give you an HTML page with the file embedded. So you wouldn't just link to that file on your webpage or something.
    – VLAZ
    Commented Mar 2, 2019 at 12:23
  • @vlaz yes, the files must be served directly, so that user provided simple html page with scripts would work
    – devondre
    Commented Mar 2, 2019 at 12:53
  • Have you searched before posting ? Have a look at this existing thread. stackoverflow.com/questions/1996122/… Let me know if it answers your query. I use htmlspecialchars for everything that output to the browser. Always filter out things when you take the request or post the response. For that the link has all the stuffs
    – Vaibs
    Commented Mar 2, 2019 at 12:53
  • @Vaibs I have searched quite a bit. Htmlspecialchars would prevent html and scripts from working. I just want to make sure that malicious script won't be able to steal cookies and do malicious xhr requests. I know I can't prevent everything, but at least sandbox it somehow
    – devondre
    Commented Mar 2, 2019 at 14:39

1 Answer 1


Commonly a fully separate domain is used to serve this kind of content so that the same origin policy of the browser kicks in and prevents interaction with the primary domain where the sensitive content is. Don't just use another subdomain because cookie policy is less strict than same origin policy and might allow reading or writing of cookies between subdomains or the main domain.

  • Thank you. I was looking for other solution which wouldn't require buying separate domain, but security should be always first - I will get another domain for user content.
    – devondre
    Commented Mar 2, 2019 at 17:03

Not the answer you're looking for? Browse other questions tagged .