PHP & mySQL: When exactly to use htmlentities?

后端 未结 4 1183
遥遥无期
遥遥无期 2020-12-04 20:14

PLATFORM: PHP & mySQL

For my experimentation purposes, I have tried out few of the XSS injections myself on my own website. Consider this situat

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 20:57

    I've been through this before and learned two important things:

    If you're getting values from $_POST/$_GET/$_REQUEST and plan to add to DB, use mysql_real_escape_string function to sanitize the values. Do not encode them with htmlentities.

    Why not just encode them with htmlentities and put them in database? Well, here's the thing - the goal is to make data as meaningful and clean as possible and when you encode the data with htmlentities like Jeff's Dog becomes Jeff"s Dog ... that will cause the context of data to lose its meaning. And if you decide to implement REST servcies and you fetch that string from DB and put it in JSON - it'll come up like Jeff"s Dog which isn't pretty. You'd have to add another function to decode as well.

    Suppose you want to search for "Jeff's Dog" using SQL "select * from table where field='Jeff\'s Dog'", you won't find it since "Jeff's Dog" does not match "Jeff"s Dog." Bad, eh?

    To output alphanumeric strings (from CHAR type) to a webpage, use htmlentities - ALWAYS!

提交回复
热议问题