Frage

I'm new to sanitizing input data, but we are starting to ramp up with number of clients very quickly, so we will need to have all user inputs sanitized, just in case, as it's a best practice.

If I've got a form that posts 12 fields, what's the best and least expensive way to sanitize it?

for simplicity's sake let's say I've got

$one = $_POST['one'];
$two = $_POST['two'];
$three = $_POST['three'];
$four = $_POST['four'];
$five = $_POST['five'];

EDIT: right here - This is getting inserted into a database under metadata. I then call to

Then I'm just calling

printf('The input for One is ' .$theNewVarForOne. '!');

But there IS a potential for malicious code in there. What's the best way to strip all iffy inputs?

EDIT:

I should have been more specific. I am basically creating some 'post' data that is stored in a database. A title, the date, the body, etc.

War es hilfreich?

Lösung

If you are printing to the screen, then HTMLspecialchars should be fine:

echo htmlspecialchars($_POST['one']);

It converts any potential malicious javascript and HTML into characters like < so that it displays as text in your source code (meaning it cannot be executed) and to the user it looks like the original input displayed on the screen:

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

If you are on the other hand inserting into a database, then you will need to do some extra work.

When inserting into a database, you really need to use prepared statements (this will stop anyone doing anything funky with SQL to your database). I prefer to use PDO to make my connection.

The code will look like this (snipped from the docs on prepare):

<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>

Andere Tipps

If you are inserting it into a database, I recommend you to use the Fluffeh's method, but a dirty quick work around is to use mysql_real_escape_string.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top