toop
toop

Reputation: 13

php escaping user input to display in html

php page1 --> below bit is pure html:

<form action="page2.php" method="post">
<input type="text" name="name" id="name">
-----------submit button, end form --etc.--------------

php page2 (and yes i have intended to stuff the text input from page1 into a hidden input in page2):

foreach($_REQUEST as $key=>$value) 
{
     $value = htmlspecialchars(strip_tags(stripslashes($value))); //attempt to cleanse the data before displaying
}
echo "<p><input type='hidden' id='name' name='name' value='".$_REQUEST['name']."'/>".$_REQUEST['name']."</p>";

The problem is that the output on page 2 is not producing w3 compliant html if the user enters input with quotes such as John O'Brien, the html becomes:

<p><input type='hidden' id='email' name='email' value='John O'Brien'/>John O'Brien</p>

I would also like to be able to produce w3 compliant html for any bad input data such as: j'o/h\n s"m,ith

Any help is appreciated!

Upvotes: 1

Views: 1823

Answers (4)

DJafari
DJafari

Reputation: 13535

foreach($_REQUEST as &$value) 
{
     $value = addslashes(htmlspecialchars(strip_tags($value)));
}
echo "<p><input type='hidden' id='name' name='name' value='".$_REQUEST['name']."'/>".$_REQUEST['name']."</p>";

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157850

  • First of all, not your code, nor any of ones posted above will ever work. For the very silly reason.
  • Next, I am kinda fixated on preserving user input exactly as is. Why delete something might be important?
  • Third, hidden values should be urlencoded I believe, rather than htmlencoded

so

$FORM = array();
foreach($_POST as $key =>$value) {
    if(get_magic_quotes_gpc()) {
        $value = stripslashes($value);
    }
    $FORM[$key] = htmlspecialchars($value,ENT_QUOTES);
}
echo "<p><input type='hidden' id='name' name='name' value='".$FORM['name']."'/>".
          $FORM['name'].
     "</p>";

Upvotes: -1

Richard JP Le Guen
Richard JP Le Guen

Reputation: 28753

Personally, I wouldn't use $_REQUEST - the book Essential PHP Security by Chris Shifflet suggests that this could make your application vulnerable to CSRF attacks.

Next, depending on server configuration, you may not have to call stripslashes(...) - see the magic_quotes_gc ini configuration. I'd use the get_magic_quotes_gpc() to determine if it is necessary.

foreach($_REQUEST as $key=>$value) {
    if(get_magic_quotes_gpc()) {
        $value = stripslashes($value);
    }
     $value = htmlspecialchars(strip_tags($value));
}
echo "<p><input type='hidden' id='name' name='name' value='".$_REQUEST['name']."'/>".$_REQUEST['name']."</p>";

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270607

Use the ENT_QUOTES option to htmlspecialchars():

$value = htmlspecialchars(strip_tags(stripslashes($value)), ENT_QUOTES);

Upvotes: 2

Related Questions