user3586157
user3586157

Reputation: 1

apostrophe in PHP string

This is weird! I have a form which gets info from a DB and then fills in a form with the details. I am trying to cater for cases where a person has a name like O'Neill. At the top of the page (outside the actual form itself) is a line that echoes the user's name to the screen:

<h2>Member Details for <?php echo $thefn; ?></h2>

And this does indeed display on the page properly, i.e., Member Details for Mike O'Neill However, in the actual form, where the code runs:

<td><?php echo "<input type='text' name='fname' value='$thefn' size='30' maxlength='30'>"; ?></td>

The name is shown with everything after the apostrophe gone! The variable is the same, so what am I doing wrong? This has got me tearing my hair out (and there's a fair amount of that!)

Upvotes: 0

Views: 4634

Answers (3)

starlocke
starlocke

Reputation: 3681

Ignoring the obvious security red herring here (I assume the format of your $thefn variable is correct for going between single quotes in HTML), I would be wrapping the PHP variables inside of {} brackets, like so. This has two major advantages. One - it is easier to spot replaceable parts, plus, makes it crystal clear to PHP what part is dynamic. Two - you can use fancier variables, like arrays. {$my_array['my_key']}.

<td>
<?php
    echo "<input type='text' name='fname' value='{$thefn}' size='30' maxlength='30'>";
?>
</td>

See also: PHP string parsing (in the manual)

Upvotes: 0

user2629998
user2629998

Reputation:

Use double quotes " " in your HTML like so :

echo "<input type='text' name='fname' value=\"$thefn\" size='30' maxlength='30'>";

Note that you have to escape them with \ since you already use double quotes to delimit your string (in PHP). Another solution is to use single-quotes on the PHP side (echo ' ';) and use double quotes inside the string, so that you don't need escaping.

Also note that this code is vulnerable to XSS attacks, you can use htmlspecialchars() to prevent that, here's the corrected code (both the XSS and the quotes) :

echo '<input type="text" name="fname" value="'.htmlspecialchars($thefn).'" size="30" maxlength="30">';

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Let's say I put in my name as:

' /><script type="text/javascript">alert("You've just been hacked!");</script><input type="hidden" name="lol" value='hax

Now what?

htmlspecialchars($thefn)

Should help.

Upvotes: 3

Related Questions