3

When I post html, js, css tag, rule, syntax's on text input. it show's up on page result!
I user $conn->real_escape_string and mysqli prepared statement but still not secure for me.

my code is:

<?php
   require 'config/config.php';
   mysqli_set_charset($conn,"utf8");
$qmsg = $_POST["qsmsg"];
$qmsgs = mysqli_real_escape_string($conn, $qmsg);
$ansr = "Answer";
$userName = "John";
$userId="4";
$userType="user";
$imgsp="images/avatar.jpg";

$stmt = $conn->prepare("INSERT INTO qa (qus, ansrq, uname, uid, utype, uimage) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssiss", $qmsgs, $ansr, $userName, $userId, $userType, $imgsp);
...
$stmt->close();
$conn->close();
?>

Result on my page:
enter image description here

12
  • 2
    You're using placeholder values, which is great, but you're also escaping, which is a mistake: That double-escapes things and damages data. Only use placeholder values and bind_param. Commented Sep 6, 2018 at 23:29
  • 1
    Remove the line with mysqli_real_escape_string, it doesn't belong and it's going to wreck your data. Commented Sep 6, 2018 at 23:35
  • 1
    That just creates a variable that's a copy of another, so that's redundant. Just pass $qmsg into bind_param and you're good to go. Commented Sep 6, 2018 at 23:38
  • 2
    Don't pre-escape, you have no idea where that data is going to end up. What if you update your application to send that over JSON? Then you need to de-escape it, then re-escape it for JSON. That's super messy. General rule: Escape it only when you're displaying it, not saving it. Commented Sep 6, 2018 at 23:45
  • 2
    @SchoolforDesign read past the specifics. "Filter input / escape output" is a general idea and not one tied to any particular technology. Commented Sep 7, 2018 at 0:03

1 Answer 1

4

This is an XSS problem, not a database or CSS problem.

The quick answer is you must call htmlspecialchars on any user data that you're displaying in an HTML context. That will neutralize any HTML a user's introduced either deliberately or by accident.

The long answer is people like to be able to put in some formatting, so consider using something like Markdown so you can type things like *bold* and _italic_ and not have to write actual HTML. There are many, many PHP implementations of this readily available.

Sign up to request clarification or add additional context in comments.

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.