0

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

1
  • “I see that the server will not execute it because of an error.” Which error? You're not trying to eval user input, are you? Commented May 2, 2011 at 13:58

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

4 Comments

I am using htmlentities now? is that not good as well? if so, this doesn't seem to work
@user: No, it's deprecated and under normal circumstances not needed and only adds extra bandwidth. You can safely echo variables containing tags and code to an HTML page using htmlspecialchars.
@Macel htmlentities() is deprecated? I was not aware that this was the case; in fact, htmlentities() encodes a greater number of characters than htmlspecialchars() (see the note at the bottom of php.net/htmlspecialchars).
@Phoenix: yes, I know, but it is not needed. Just use correct encoding and you'll be fine. The only characters that need to be encoded are <, > and &.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.