1

i am using this code

<?php
include('connection.php');
$heading = $_POST['upd_head'];
$note =  $_POST['upd_text'];
$post_id = $_POST['up_post_id'];
$supd_head= "UPDATE posts SET heading= ?, note=? WHERE post_id=?";
$stmt_head= mysqli_stmt_init($db_conx);
if(!mysqli_stmt_prepare($stmt_head, $supd_head)){
echo "sql is not ready";
 }
else{
mysqli_stmt_bind_param($stmt_head, "sss", $heading,$note,$post_id);
mysqli_stmt_execute($stmt_head);
}

?>

when i give this input

<script>alert('hack');</script>

it saves as it is in the database and gives an alert message when i refresh page after updating data. Why its not sanitizing the data first? But i think there is no use of mysqli_real_escape_string when using prepare statement.

  • how are you echoing out the variable? – treyBake Oct 17 '18 at 10:22
  • 1
    _“Why its not sanitizing the data first?”_ - because that’s absolutely not its job …? Its job is to make sure that whatever data you throw at it, it doesn’t cause a problem while inserting that data into the database. _“and gives an alert message when i refresh page after updating data”_ - that’s because you did not treat the data properly while _outputting_ it onto the page. The database has little to nothing to do with that. – misorude Oct 17 '18 at 11:09
  • thanku for ur answer now i have understood – nitin verma Oct 17 '18 at 13:08

1 Answers1

1

mysqli_stmt_prepare is not made to prevent Cross Site Scripting (XXS)

It all depends on how you display the data. The link above shows an example:

echo htmlspecialchars($string, ENT_QUOTES, 'UTF-8');

A lot of information can be find on the OWASP website

Loko
  • 6,539
  • 14
  • 50
  • 78
  • but it saves data as it is in database – nitin verma Oct 17 '18 at 11:01
  • Why should it _not_ be safe? – misorude Oct 17 '18 at 11:10
  • means it safe. actually i have not so much knowledge about sql injection that is why i thought any special char input can cause sql injection but using prepare statement i think it will be safe to remove mysqli_real_escape_string ? – nitin verma Oct 17 '18 at 11:19
  • @nitinverma Look, we're talking about database and the application. The database sees this as just text. It's not gonna interpret this as javascript. When you run the query and show the result in a php or html file, it will render it as javascript. At that point of time you're gonna need to encode it like my answer and the links say so. – Loko Oct 17 '18 at 11:30
  • it means no worry about sql injection when using mysqli prepare statement – nitin verma Oct 17 '18 at 12:01
  • @nitinverma Yes and the problem you're describing has nothing to do with SQL injection. – Loko Oct 17 '18 at 12:19
  • just curious to know how can i output data having special character as it is after sanitising using mysqli_real_escape_string ? – nitin verma Oct 17 '18 at 14:46