Search code examples
phpmysqlinputquotes

PHP, MySQL, quotes and inputs fields


I'm trying to build an edit page to edit a title.

This title would be displayed in both an "h3" tag and an input field. When the user is happy with the title, he submits it to mysql where it is saved. The page refreshes and he can see his new title within the "h3" tag and the input field.

The problem is that, when quotes are involved in the title, I don"t get the same result in the "h3" tag and the input field.

Here is how I retrieve the variable to send it to the database:

$title_set = $_POST['title'];

And here is how I display the variable in both the tag and input field:

$title_get = $result['denomination'];

With this here is the display for the title: L'appel de la "forêt"

$title_set = $_POST['title'];
$title_get = $result['denomination'];

<h3>  -> No output
Input -> No output

Variation 1:

$title_set = addslashes($_POST['title']);
$title_get = $result['denomination'];

<h3>  -> L'appel de la "forêt"
Input -> L'appel de la

Variation 2:

$title_set = addslashes($_POST['title']);
$title_get = stripslashes($result['denomination']);

<h3>  -> L'appel de la "forêt"
Input -> L'appel de la

Variation 3:

$title_set = mysql_real_escape_string ($_POST['title']);
$title_get = $result['denomination'];

<h3>  -> L'appel de la "forêt"
Input -> L'appel de la

Obviously, there are differences in the way a title tag and an input field manage to display dynamic data with quotes, input fields being more restrictive.

So, what should I do?

My pages, scripts and database are encoded in UTF_8


Solution

  • Before inserting data to the database, use an escaping function like mysql_real_escape_string(). Or even better, switch to PDO so you can use prepared queries and submit the data as a parameter. This protects against SQL injection. See How can I prevent SQL-injection in PHP?

    Before echoing to HTML the dynamic content you fetched from the database, encode it with htmlspecialchars(). This protects against Cross-Site Scripting (XSS). See How to prevent XSS with HTML/PHP?

    Further reading: https://www.owasp.org/index.php/OWASP_Top_Ten_Cheat_Sheet for more on injection and XSS risks and remedies.