When exactly to use htmlspecialchars in php?

by 6 replies
8
What exactly is the use of htmlspecialchars in php and when to use that while developing a web site. Is it to be use before storing data to data base or after retrieving from the database.
#programming #htmlspecialchars #php
  • You should only call this method when echoing the data into HTML.

    Don't store escaped HTML in your database; it will just make queries more annoying.
    The database should store your actual data, not its HTML representation.

    Source: php - when to use htmlspecialchars() function? - Stack Overflow
    • [ 1 ] Thanks
  • See: http://php.net/htmlspecialchars should be added before storing to the db.

    The purpose of htmlspecialchars is to avoid MySQLinjection.
    This is to add security for your database.

    I hope this answers your query.

    If you have further questions, please visit my page and message me.

    Thanks!
  • From my understanding of PHP, there's a difference between htmlspecialchars and an SQL Injection. Even though they are both PHP functions, they are both used for different purposes.

    htmlspecialchars, a string function, converts all special characters to html code, for example < is converted to &lt; and > (less-than sign) is converted to &gt; (greater-than sign).

    mysql_real_escape_string, a MySQL function, takes a string that is going to be used in a MySQL query and returns the same string with all SQL Injection attempts safely escaped.
    • [1] reply
    • @jeffreysloe Hi! Thanks for the reply. You mean htmlspecialchars is to be used before delivering data to the browser?
      • [1] reply
  • When HTML validation from W3C is a priority then this htmlspecialchars function will help you much. Any anchor links without converting by htmlspecialchars will be complained.

Next Topics on Trending Feed