Jump to content

Sanitizing a string coming from user input, help and suggestion.


nightkarnation

Recommended Posts

Hey Guys...

I have a simple question,

I want to sanitize a simple string that can have standard letters from a-zA-Z numbers 0-9 and these two characters -_

 

I am testing the following:

 

$var="<b>Peter_13-<b>";

var_dump(filter_var($var, FILTER_SANITIZE_STRING));

 

But that turns $var to echo: string(17) "Peter_13-"

I just want it to sanitize and clean up to: Peter_13-

Is there a simple way to sanitize like this?

 

In other words...I am receaving from a swf file communicating to php... like this:

 

//variable comming from flash:
$username=mysql_real_escape_string($_POST['Username']);
//and now I would like to sanitize this variable and be sure that is nothing harmful ($username will be saved to mysql after...) 

 

Thanks a lot in advance!!

Cheers.

Link to comment
Share on other sites

Sorry Pikachu, I made a horrible explanation...

Here it goes again, with a detailed and simple example:

 

...
//grab variables coming from flash in my case... (from client)
$username=mysql_real_escape_string($_POST['Username']);
$email=mysql_real_escape_string($_POST['Email']);
$first_name=mysql_real_escape_string($_POST['FirstName']);
$last_name=mysql_real_escape_string($_POST['LastName']);
$activation_number=mysql_real_escape_string($_POST['ActivationNumber']);

//SANITIZE
filter_var($username, FILTER_SANITIZE_STRING);
filter_var($email, FILTER_SANITIZE_EMAIL);
filter_var($first_name, FILTER_SANITIZE_STRING);
filter_var($last_name, FILTER_SANITIZE_STRING);
filter_var($activation_number, FILTER_SANITIZE_NUMBER_INT);

$result = mysql_query("INSERT INTO `login` (Username, Email, First_Name, Last_Name, Activation_Number) VALUES ('$username', '$email', '$first_name', '$last_name', '$activation_number')");
...

 

Now my question is the following, Am I sanitazing client input correctly? Am I inserting the data that is coming from my clients safe for my queries??

Thanks a lot for any suggestions!!!

Link to comment
Share on other sites

No, your question was pretty clear.

 

mysql_real_escape_string() is used specifically for the purpose of making string data safe to use in a query.

 

What makes you think you need to use filter_var() functions for string values to use them in a query?

 

The one value that should be treated differently is $_POST['ActivationNumber'] because it's evidently an integer. From the rest of your code, it looks like all you really need to do with it is validate it contains only digits and cast it as an integer.

$activation_number = ctype_digit($_POST[['ActivationNumber']) ? (int) $_POST['ActivationNumber'] : FALSE;

And remove the quotes from '$activation_number' in the query string.

 

As a side note, you should also validate that all the incoming data is of the type expected, and within any required parameters, if applicable.

Link to comment
Share on other sites

Personally, I always used prepared statements:

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    foreach($dbh->query('SELECT * from FOO') as $row) {
        print_r($row);
    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
// Retrieve values
$val1 = htmlentities($_POST['some_value'],ENT_QUOTES); // a string
$val2 = (int)$_POST['some_value2']; // an integer
$sql = "INSERT INTO `table` (someVal1, someVal2,...) VALUES(:val1,:val2,...)";
try{
$stmt = $dbh->prepare($sql);
// Sanitize values into query
$stmt->bindParam(":val1",$val1,PDO::PARAM_STR);
$stmt->bindParam(":val2",$val2,PDO::PARAM_INT);
$stmt->execute();
}catch(Exception $e){
die($e->getMessage());
}
?>

I only share because I've read that this is one of the more secure ways to handle data.

Link to comment
Share on other sites

Hey Guys! thanks a lot for the help and suggestions!!

I have improved a lot my script in terms of validation, sanitization...

I would really appreciate if Pikachu and/or any other experienced member can tell me if I am going in the right direction:

Heres the code:

 

if(isset($_POST['Username']) && sanityCheck($_POST['Username'], 'string', 15) != FALSE)
    {
	$username = strip_tags(substr(mysql_real_escape_string($_POST['Username']),0,32));
	$validation = true;
    }
else
    {
	$validation = false;
                $imdoneUpdate = false;
	echo "imdoneUpdate=".$imdoneUpdate;
	exit();
    }
if(isset($_POST['Email']) && sanityCheck($_POST['Email'], 'string', 256) != FALSE && checkEmail($_POST['Email']) != FALSE)
    {
	$validation = true;
	$email=mysql_real_escape_string($_POST['Email']);
    }
else
    {
	$validation = false;
                $imdoneUpdate = false;
	echo "imdoneUpdate=".$imdoneUpdate;
	exit();
    }
if(isset($_POST['FirstName']) && sanityCheck($_POST['FirstName'], 'string', 30) != FALSE)
    {
	$validation = true;
	$first_name=mysql_real_escape_string($_POST['FirstName']);
    }
else
    {
	$validation = false;
                $imdoneUpdate = false;
	echo "imdoneUpdate=".$imdoneUpdate;
	exit();
    }
if(isset($_POST['LastName']) && sanityCheck($_POST['LastName'], 'string', 40) != FALSE)
    {
	$validation = true;
	$last_name=mysql_real_escape_string($_POST['LastName']);
    }
else
    {
	$validation = false;
                $imdoneUpdate = false;
	echo "imdoneUpdate=".$imdoneUpdate;
	exit();
    }
if(isset($_POST['ActivationNumber']) && sanityCheck($_POST['ActivationNumber'], 'numeric', 11) != FALSE)
    {
	$validation = true;
	$activation_number=mysql_real_escape_string($_POST['ActivationNumber']);
    }
else
    {
	$validation = false;
                $imdoneUpdate = false;
	echo "imdoneUpdate=".$imdoneUpdate;
	exit();
    }



//SANITIZATION

$username = filter_var($username, FILTER_SANITIZE_STRING);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$first_name = filter_var($first_name, FILTER_SANITIZE_STRING);
$last_name = filter_var($last_name, FILTER_SANITIZE_STRING);
$activation_number = filter_var($activation_number, FILTER_SANITIZE_NUMBER_INT);


if( $validation == true )
{

$result = mysql_query("INSERT INTO `login` (Username, Email, First_Name, Last_Name, Activation_Number) VALUES('$username', '$email', '$first_name', '$last_name', '$activation_number')");

}


//VALIDATION SECTION
//---------------------------------------------------------------------------------------------------------------
//validate string and numeric variables
function sanityCheck($string, $type, $length)
{
  // assign the type
  $type = 'is_'.$type;

  if(!$type($string))
    {
    return FALSE;
    }
  // if there is anything in the string
  elseif(empty($string))
    {
return FALSE;
    }
  // check how long the string is
  elseif(strlen($string) > $length)
    {
    return FALSE;
    }
  else
    {
    // if all is well, return TRUE
    return TRUE;
    }
}

//VALIDATE EMAIL
function checkEmail($email){
  return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}

 

One more thing...Am I placing correctly the mysql_real_escape_string in terms of sequence/processing ?

Thanks a lot in advance!!

Cheers!

Link to comment
Share on other sites

Why are you still using filter_var( $whatever, FILTER_SANITIZE_STRING ) for anything? Maybe if you tell us what you think it's actually doing, someone can explain why it shouldn't be there (if that turns out to be the case).

Link to comment
Share on other sites

Well just in case the validation went through ok and there is still some unaccepted character, the sanitization will take it out of the incoming variable going to the database??

 

If I am incorrect, then should I erase the sanitization process and just leave the validation and mysql escape string, is this good enough?

 

Thanks a lot!!!

Link to comment
Share on other sites

I want to strip suspicious characters thats all...

And (yes) I am safe with only having letters, numbers, underscores and hyphens...though some other characters wont be stripped, which is fine with me...as long they are safe...

But please let me know if the whole process is a good way of preventing malicious client input? what do u think?

Thanks again!!!

Link to comment
Share on other sites

Ok Pikachu, thanks a lot for your kind help!

 

Here's a doubt I have...

In my case:

$Activation_Number has numerical values (At least, numerical values are expected on the validation) but on my database the type is varchar ... should I mysql real escape it ??

I know it would be logical to change it from my database to INT type, but I am trying to undestand the difference between escaping strings or numbers...

The difference of doing that is linked to the type of the field on the db, right?

for ex, Username = type: Varchar (should mysqlrealescape on php...)

Id = type: INT  (should validate as only numeric values and use the function you told me before, right??)

 

Thanks again!!!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.