简体   繁体   English

如果我从 php 回显数据,如何防止将有害数据注入 img src?

[英]how do I prevent harmful data from being injected into img src if I echo data from php?

A little background of this problem wouldn't hurt I think:我认为这个问题的一点背景不会受到伤害:
I have a webservice to which I can upload images and then retrieve them by id via an api call.我有一个网络服务,我可以向其中上传图像,然后通过 api 调用按 id 检索它们。 The return value is a link to an actual image on the server.返回值是指向服务器上实际图像的链接。 However, that data is easy to substitute if the request is hijacked.但是,如果请求被劫持,该数据很容易替换。

So the problem that arises from this is that you can replace the link with " onerror="alert(whatever);因此由此产生的问题是您可以将链接替换为" onerror="alert(whatever); and it would alert the user with 'whatever' because this link is placed into <img src="<?= api/get.php?image_id=x?>" /> becoming <img src="" onerror"alert(whatever);" />它会用'whatever'提醒用户,因为这个链接被放入<img src="<?= api/get.php?image_id=x?>" />变成<img src="" onerror"alert(whatever);" /> <img src="" onerror"alert(whatever);" /> . <img src="" onerror"alert(whatever);" /> .

How do I go about preventing that from happening?我如何防止这种情况发生? Is there a way to maybe escape the link before inserting it into the image tag?有没有办法在将链接插入图像标签之前转义链接? Or better yet base64 the link?还是更好的 base64 链接?

I have tried and failed using:我尝试过使用但失败了:
1. urlencode() 1. urlencode()
2. base64_encode() 2.base64_encode()

Any help is appreciated!任何帮助表示赞赏! Thanks!谢谢!

PS I cannot send base64 encoded images since I need to able to copy image's link easily. PS 我无法发送 base64 编码图像,因为我需要能够轻松复制图像的链接。

As I was writing this question SO suggested some related topics where I found out that htmlspecialchars() works wonderfully solving this problem.在我写这个问题的时候,我提出了一些相关的话题,我发现htmlspecialchars()可以很好地解决这个问题。 However, this still might not be enough because this only works for my use-case, not every possible one.但是,这可能还不够,因为这仅适用于我的用例,而不是所有可能的用例。 Please feel free to suggest more solutions.请随时提出更多解决方案。

It sounds like the first problem is you are allowing a user to control the filename.听起来第一个问题是您允许用户控制文件名。 If you are controlling and hosting the uploads, generate a guid and use that to store the file.如果您正在控制和托管上传,请生成一个 guid 并使用它来存储文件。 Removing the ability for users to control the filename removes the chance they can add a " to break out of your <img src" context.删除用户控制文件名的能力会删除他们可以添加"打破您的<img src"上下文的机会。

I don't see why urlencode() would fail.我不明白为什么urlencode()会失败。 As long as a " is displaying as %22 that will prevent that data from breaking out of the attribute context.只要"显示为%22 ,就可以防止该数据脱离属性上下文。

You also do need to ensure that <> characters are encoded as well.您还需要确保<>字符也被编码。 For this you may want to use htmlentities()为此,您可能需要使用htmlentities()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM