-2

Just wanted to test mysqli_real_escape_string. I was expecting the script embedded in $string to not work. However I can see the alert message.

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "test_db";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    // Check connection
    if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
    }

    $string = "<script>alert('This is script from php')</script>";
    echo mysqli_real_escape_string($conn,$string);
?>

As far as I know that mysqli_real_escape_string should stop the script from execution. Is there a better way. I know about the prepared statements .. anything apart from that I shoud do?

** NOT SIMILIAR AS This one **

  • 1
    [From the docs](https://www.w3schools.com/Php/func_mysqli_real_escape_string.asp): "The function escapes special characters in a string **for use in an SQL query**". This does mean it will strip HTML tags. For that, you should look at [`strip_tags`](https://www.php.net/manual/en/function.strip-tags.php). – Matt Clark Feb 04 '20 at 06:32
  • @MattClark thats not correct, this function doesn't strip HTML tags, it just escapes the special characters to prevent a SQL injection. – CodyKL Feb 04 '20 at 06:55

1 Answers1

1

mysqli_real_escape_string is used to prevent SQL Injection .

what you want to do is preventing XSS because the <script> tag so you should use

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

Abolfazl Ghaemi
  • 424
  • 2
  • 14
  • 1
    real_escape_string should not be used to prevent SQL injection. This is not what it's for. – Dharman Feb 04 '20 at 07:46
  • its not a good way to prevent SQL Injection with mysqli_real_escape_string . but it does prevent SQL Injection . always the best way is prepared statement . – Abolfazl Ghaemi Feb 04 '20 at 08:10