In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?

前端 未结 6 1923
说谎
说谎 2020-11-22 03:18

I am working on a form with the possiblity for the user to use illegal/special characters in the string that is to be submitted to the database. I want to escape/negate thes

6条回答
  •  渐次进展
    2020-11-22 03:54

    If you submit this data to the database, please take a look at the escape functions for your database.

    That is, for MySQL there is mysql_real_escape_string.

    These escape functions take care of any characters that might be malicious, and you will still get your data in the same way you put it in there.

    You can also use prepared statements to take care of the data:

    $dbPreparedStatement = $db->prepare('INSERT INTO table (htmlcontent) VALUES (?)');
    $dbPreparedStatement->execute(array($yourHtmlData));
    

    Or a little more self explaining:

    $dbPreparedStatement = $db->prepare('INSERT INTO table (htmlcontent) VALUES (:htmlcontent)');
    $dbPreparedStatement->execute(array(':htmlcontent' => $yourHtmlData));
    

    In case you want to save different types of data, use bindParam to define each type, that is, an integer can be defined by: $db->bindParam(':userId', $userId, PDO::PARAM_INT);. Example:

    $dbPreparedStatement = $db->prepare('INSERT INTO table (postId, htmlcontent) VALUES (:postid, :htmlcontent)');
    $dbPreparedStatement->bindParam(':postid', $userId, PDO::PARAM_INT);
    $dbPreparedStatement->bindParam(':htmlcontent', $yourHtmlData, PDO::PARAM_STR);
    $dbPreparedStatement->execute();
    

    Where $db is your PHP data object (PDO). If you're not using one, you might learn more about it at PHP Data Objects.

提交回复
热议问题