Reputation: 450
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 it 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
Upvotes: 0
Views: 8798
Reputation: 21763
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:
<?php echo 'hi'; ?>
Upvotes: 4
Reputation: 91983
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.
Upvotes: 2