phpsecurity

How to stop the user from entering harmful codes?


How do I totally stop the users from entering some crazy SQL injections? Isn't mysql_real_escape_string powerful enough to stop it? I followed some guidelines, though there were some users in here who criticized my code and gave me a thumbs down for the security. I was unable to understand the reason behind it. Though I am not using $_GET, the only user input is through the commenting system. I just want to make sure I am not going wrong. Here is my sample code.

$name = htmlspecialchars(strip_tags(mysql_real_escape_string($_POST['com_name'])));

I have used the same for some 5 fields. What is your take on my above code?


Solution

  • The idea is not to stop the users from entering it, but to make sure you enter them in the database query safely. This means using mysql_real_escape_string or using parameterized queries with mysqli:

    /* Prepare an insert statement */
    $query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
    $stmt = mysqli_prepare($link, $query);
    
    mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);
    

    You also need to make sure your properly html encode fields you read from the database, to avoid that the user is able to inject html (and also javascript)