user2654458
user2654458

Reputation: 23

Can I safely output data to the user using this sanitize

So im trying to work out the best way to sanitize xss for safe output to the user.

More or less, when storing values from a form, im using strip_tags(); then bind_params();

And when Im about to output the data to the user Im also using htmlentities();

The data will only be shown inside <p> and <a> tags.

eg:

<p> Some data from user </p>

<a href=""> Some data from user </p>

Should this work?

Index.php

<form action="sante.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>

And then sante.php

<?php

$name = $_POST["fname"]; 
$age = $_POST["age"];

$namn = strip_tags($name); // then storing into mysql with bind_param
$older = strip_tags($age); // then storing into mysql with bind_param


 // before output, htmlentities

   function safe( $value ) {
  htmlentities( $value, ENT_QUOTES, 'utf-8' );

  return $value;
}


// Now showing values

echo safe($namn). "<br>";

echo "<p>" .safe($older) . "</p>";


?>

Upvotes: 2

Views: 255

Answers (2)

merdincz
merdincz

Reputation: 448

When you insert data to database you must use mysql_real_escape_string or use PDO, if you display data you must use htmlspecialchars

Upvotes: 0

user428517
user428517

Reputation: 4193

Yes, you can use this code safely. I see you're already using bind_param (and I assume either the mysqli or PDO library), which prevents SQL injection (damage to you), and htmlentities, which prevents cross-site scripting (damage to the user).

You don't even need to call strip_tags before writing to the database, although it's a fine idea if you don't want user input to contain any JS/PHP/HTML tags at all (and also if you forget to call your safe function on output).

Upvotes: 1

Related Questions