Is the following good enough to avoid a SQL injection?
mysql_real_escape_string(htmlentities (urlencode($_POST['postmessage'])));
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I think that you are confusing two security issues: SQL injection and cross-site scripting (XSS).
A website is vulnerable to SQL injection when improperly sanitized user input is used in an SQL query that is sent to the SQL database. This code, for example, introduces an SQL injection vulnerability:
This problem is easy to fix by escaping the user input with a function like
mysql_real_escape_string:That’s all that you need to do, but the tricky part is remembering to do this for every piece of user input that is used in an SQL statement.
A website is vulnerable to cross-site scripting when user input is used in HTML that is sent to a client. This code, for example, introduces a XSS vulnerability:
A XSS vulnerability is fixed by escaping the user input with a function like
htmlspecialchars:Again, this is easy to do, but easily forgotten.
Usually, user input that is placed in a database to be used in sending back HTML at a later time is saved unmodified. That is, only
mysql_real_escape_stringis used. However, you could escape user input to prevent XSS, and then escape the XSS-safe string to prevent SQL injection:The benefit is that you don’t need to remember to escape values from the database with
htmlspecialcharsbefore writing them into HTML. The drawback is that some values may need to be escaped with different functions. For example, a user name would probably be escaped withhtmlspecialchars, but a "postmessage" might allow BBcode, Markdown, or a subset of HTML. If you escaped all input to prevent XSS, then you would need to unescape values from the database with, for example,htmlspecialchars_decode.One problem is that unescaping the escaped string does not always return the original string (
unescape(escape($orig))is not necessarily the same as$orig). Even withhtmlspecialcharsandhtmlspecialchars_decode, using a different quote style will cause this problem. Another example is that ifstrip_tagsis used, then information is removed irrecoverably; you will not be able to undo thestrip_tags. Thus, many developers choose to usemysql_real_escape_stringonly to save values into the database andhtmlspecialchars(or whatever) to prepare a string from the database to be used in HTML.