Dealing with apostrophes and quotation marks for forms and output with PHP


I have run into the same annoying problem for a long time and finally found an easy solution. Whenever forms are submitted via PHP (by a user or myself) and apostrophes or quotation marks are added in forms, they are escaped using mysqli_real_escape_string and entered into the database without a hitch. However, when outputting the data from the database, any text or strings suddenly get cut off, disappear or don’t work wherever the apostrophe and quotations appear.

htmlspecialchars to the rescue! Rather than a simple echo of the text or string directly from the database, use htmlspecialchars() around the string to convert apostrophes and quotation marks into ASCII strings and does not mess with the PHP markup.

 

for example:

<?php

$string =  row['string'];

echo htmlspecialchars($string);

?>

 

 


Leave a Reply

Your email address will not be published. Required fields are marked *