Page 1 of 1

Validating large amount of strings

Posted: Mon Oct 23, 2006 1:51 am
by Mr Tech
Let's say this is my mysql_query:

Code: Select all

mysql_query("update orders set contact_fname='$_POST[contact_fname]', contact_lname='$_POST[contact_lname]', contact_company='$_POST[contact_company]', contact_email='$_POST[contact_email]', contact_phone='$_POST[contact_phone]', contact_fax='$_POST[contact_fax]', contact_address='$_POST[contact_address]', contact_city='$_POST[contact_city]', contact_state='$_POST[contact_state]', contact_postcode='$_POST[contact_postcode]', contact_country='$_POST[contact_country]' where orderid='$orderid'") or die(mysql_error());
Is there a better way to validate those to stop SQL ingections, XSS etc other than validating one at a time like:

Code: Select all

$contact_fname = makesafe($_POST[contact_fname]);
$contact_lname = makesafe($_POST[contact_lname]);
etc etc
I'm not sure if there are proper ways to do this... Is it better the validate one at a time or not?

If you could sehd some light, it would be greatly appreciated...

Posted: Mon Oct 23, 2006 2:08 am
by timvw
It's not validating, but simply 'preparing' for use in a mysql query:

Code: Select all

$prefix = 'contact_';
$required_keys = array('name', 'lname', 'company', ...);

$mysql = new array();

foreach($required_keys as $key) {
 if (!isset($_POST[$prefix . $key])) {
  throw new MissingKeyException("the key " . $prefix . $key . " is missing.");
 }
  $mysql[$key] = mysql_real_escape_string($_POST[$prefix . $key]);
}

// now all the values are in $mysql...
Later on when you want to use the data for use in html:

Code: Select all

$html = new array();

foreach($required_keys as $key){
 $html[$key] = htmlentities($_POST[$prefix . $key], ENT_QUOTES, 'UTF-8');
}

// now all the values are in $html...

Posted: Mon Oct 23, 2006 2:18 am
by Mr Tech
Thanks Tim.

Does mysql_real_escape_string() need to be used whenever something is inserted into the database?

Also, what's the difference between mysql_real_escape_string() and addslashes()? Is mysql_real_escape_string() only for MySQL?

Posted: Mon Oct 23, 2006 3:47 am
by s.dot
Mr Tech wrote:Thanks Tim.

Does mysql_real_escape_string() need to be used whenever something is inserted into the database?

Also, what's the difference between mysql_real_escape_string() and addslashes()? Is mysql_real_escape_string() only for MySQL?
mysql_real_escape_string() should ALWAYS! be used on user data being inserted into a database.

addslashes() will only prepend slashes to quotes. mysql_real_escape_string() escapes other potentially unsafe characters as well such as \x00, \n, \r, \, and \x1a