20

I've got a php variable like so.. $name = $_REQUEST['name']; I'd like to put it in a HTML form field's value e.g in here.. <input type="text" name="name" value=(php variable here) /> How would I do so?

Thanks.

Skizit
  • 43,506
  • 91
  • 209
  • 269

2 Answers2

45
value="<?php echo htmlspecialchars($name); ?>"
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
10

You can do it like this,

<input type="text" name="name" value="<?php echo $name;?>" />

But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.

<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />
Rich Adams
  • 26,096
  • 4
  • 39
  • 62
  • Short tags are deprecated and that opens up a lovely world of XSS (since $name is clearly indicated as user generated content in the code provided in the question) – Quentin Jul 23 '10 at 11:36
  • 1
    Thanks, I noticed the sanitizing once I'd answered and was already updating when you posted this comment ;) I've updated my answer to remove the short tags after your comment though. I know they're deprecated, but I still use them so it was just automatic to type it out that way. – Rich Adams Jul 23 '10 at 11:43
  • That isn't properly sanitized. Quotes are still allowed and you didn't set the character set. – user3148596 Feb 11 '14 at 08:24