dihakz
dihakz

Reputation: 557

PHP to output single and double quotes as a value for an input element

I have a value ($title) that is stored in MySQL and is being called, using PHP, to be inserted into the value of an input element. The problem is when a single or double quote is used, the value of the input field terminates at that point.

The behavior that should occur is the input field should be populated EXACTLY with the data in the $title variable, so that when the form is updated, the quotes remain intact.

Here is the PHP:

<?php
    echo '<input type=text size=91 name=title value="'.stripslashes($title).'">';
?>

Now, here is a typical problem: if the value of $title

this is a test " of what occurs with a quote

and I echo the variable, it echos correctly to

this is a test " of what occurs with a quote

However, when used in an input field, it renders as:

<input value="this is a test " of what occurs with a quote">

The first " terminates the value of the field, causing the new value to be:

this is a test 

I'm confused as to how to get the proper value to display and be submitted with the form, when that variable is displayed and updated.

Upvotes: 8

Views: 15815

Answers (5)

cb0
cb0

Reputation: 8613

Try using htmlspecialchars. This will escape the " in yout title.

value="'.htmlspecialchars($title).'">

Upvotes: 13

Kalyan02
Kalyan02

Reputation: 1434

After you perform stripslashes you should use htmlspecialchars to escape the special characters. This avoids the mess the characters like ",', etc might otherwise create.

<input type=text size=91 name=title value="'.htmlspecialchars(stripslashes($title)).'">

The above snippet will only fix it for display purpose. But when the submit happens you must use either mysql_real_escape_string() or $pdo->quote() to escape the special characters before you run the SQL query.

Upvotes: 0

landons
landons

Reputation: 9547

Why are you running stripslashes()? Running addslashes() (the opposite function) would fix this particular issue, but a better approach would be to use htmlentities($title, ENT_COMPAT, 'utf-8') everywhere you output the title (or, if your structure allows, when the data is stored).

Upvotes: 0

Amar Banerjee
Amar Banerjee

Reputation: 5012

Change this line.

<input type=text size=91 name=title value="'.stripslashes($title).'">

To

<input type=text size=91 name=title value=\''.stripslashes($title).'\'>

Upvotes: 1

Albzi
Albzi

Reputation: 15609

Put a \ before the quote.

echo "This is a \" test";

Upvotes: 2

Related Questions