Search code examples
phphtmlspecialchars

PHP's htmlspeciachars not working on single quotes


I'm trying to convert a single quote into its relevant HTML code for database insertion, but it does not appear to be working. When I create the following script:

<?php
 $str = "& and ' and \" and < and >";
 echo htmlspecialchars($str);
?>

My browser returns the following:

&amp; and ' and &quot; and &lt; and &gt;

What am I doing wrong? I've read the PHP manual on htmlspecialchars() function and it says it applies to single quotes, but it doesn't seem to be working for me.


Solution

  • Use htmlentities() with the flag ENT_QUOTES. From the manual:

    ENT_QUOTES Will convert both double and single quotes.

    htmlentities($text, ENT_QUOTES);
    

    If you just want to replace ' to &#39; you could use str_replace(), of course:

    str_replace("'", "&#39;", $text);
    

    However, since you want to insert the data into SQL code, please look into prepared statements in PDO or MySQLi. These functions serve the exact purpose you need (from what I can tell) and will be better than your own function. After all, why reinvent the wheel?

    Just for the record, be sure not to use the deprecated MySQL functions in PHP – as explained in _Why shouldn't I use mysql__* functions in PHP?.