when to use htmlspecialchars() function?

前端 未结 4 1996
自闭症患者
自闭症患者 2020-11-28 09:06

Hi I was wondering when is the appropriate place to use htmlspecialchars(). Is it before inserting data to database or when retrieving them from the database?

4条回答
  •  死守一世寂寞
    2020-11-28 09:13

    Guide - How to use htmlspecialchars() function in PHP

    To begin you have to understand 1 simple concept: Render.

    What Render is? Render is when the HTML transforms

    Hello
    

    to bold like this Hello. That's render.

    So...When to use the htmlspecialchars() function?

    Wherever you want to render HTML contents. For example, if you are using JQuery and you do this:

    $("#YourDiv").html("Hello");
    

    The div contents will be Hello. It rendered the text into HTML.

    If you want to display the message in this way (was wrote by user):

    Hello
    

    you have to put:

    $("#YourDiv").text("Hello");
    

    In that way the Hello will never be rendered.

    If you want to load the message (as wrote by user) into a textbox, textarea, etc... You have to put:

    
    
    
    

    That will display

     Hello
    

    Inside the Textbox without problems.

    Conclusion:

    What ever data the user input into your forms, etc...Save the data as normally. Do not use any function. If user sent 12345 save as it is. Do not filter nothing. You only have to filter when you are going to display the data in the page to the users. YOU, ONLY YOU decide if you want to render or not what the user wrote. *Remember that.

    Regards!

提交回复
热议问题