开发者

preventing php injection in forms (if a user submits php code into a form)

开发者 https://www.devze.com 2023-03-01 21:23 出处:网络
In a contact form, if someone enters the following into the textbox: <?php echo \'hi\'; ?> I see that the server will not execute it because of an error. What I would like it to do is instead

In a contact form, if someone enters the following into the textbox:

<?php echo 'hi'; ?>

I see that the server will not execute it because of an error. What I would like it to do is instead, somehow escape i开发者_StackOverflow社区t into plain text and display it correctly. I have seen other sites been able to do this. I originally thought this could be solved by the addslashes() function, but that doesn't seem to work.

Thanks, Phil


No. Use htmlspecialchars instead. Don't use addslashes.

To be more specific, addslashes bluntly escapes all instances of ', " and \ and NUL. It was meant to prevent SQL injection, but it has no real use in proper security measures.

What you want is preventing the browser to interpret tags as is (and that's entirely different from preventing SQL injections). For instance, if I want to talk about <script> elements, SO shouldn't simply send that string literally, causing to start an actual script (that can lead to Cross-site scripting), but some characters, especially < and >, need to be encoded as HTML entities so they're shown as angle brackets (the same is true for &, that otherwise would be interpreted as the start of an HTML entity).

In your case, output after htmlspecialchars would look like:

&lt;?php echo 'hi'; ?&gt;


Use htmlspecialchars before outputing anything provided by the user. But in this case, also make sure that you do not execute anything the user inputs. Do not use eval, include or require. If you save the user data to a file, use readfile or file_get_contents+htmlspecialchars instead of include/require. If you're using eval, change it into echo and so on.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号