FRIHOSTFORUMSSEARCHFAQTOSBLOGSCOMPETITIONS
You are invited to Log in or Register a free Frihost Account!


Question about safe input from text boxes





oly0015
Just trying to make a guestbook kind of interface for a website and I came to the idea of making a function to make sure the string is safe so it will not kill off the site. I managed to find this online and added a little bit to it and was wondering if anyone had something better or any ideas?


if(get_magic_quotes_gpc())
{
$string = stripslashes($string);
}
if (phpversion() >= '4.3.0')
{
$string = mysql_real_escape_string($string);
}
else
{
$string = mysql_escape_string($string);
}
$badWords = //This is just swear words and SQL terms
$string = eregi_replace($badWords, "", $string);
$string = htmlentities($string, ENT_QUOTES);
coreymanshack
oly0015 wrote:
Just trying to make a guestbook kind of interface for a website and I came to the idea of making a function to make sure the string is safe so it will not kill off the site. I managed to find this online and added a little bit to it and was wondering if anyone had something better or any ideas?


if(get_magic_quotes_gpc())
{
$string = stripslashes($string);
}
if (phpversion() >= '4.3.0')
{
$string = mysql_real_escape_string($string);
}
else
{
$string = mysql_escape_string($string);
}
$badWords = //This is just swear words and SQL terms
$string = eregi_replace($badWords, "", $string);
$string = htmlentities($string, ENT_QUOTES);


I would not use the following,
Code:
if (phpversion() >= '4.3.0')
  {
    $string = mysql_real_escape_string($string);
  }
  else
  {
    $string = mysql_escape_string($string);
  }

You are coding your own guestbook, you know what php version your host is running. If your host is running lower than version 4.3.0 run away and never look back.
Take out that whole block and just put

Code:
$string = mysql_real_escape_string($string);


You also know if your host has magic quotes enabled by default or not, if you don't look in the phpinfo();
Most web hosts don't enable this by default. It is up to the programmer to sanitize the data correctly.
I doubt your host is using magic quotes, so remove that block of code.

When you don't need to use regex in your string replacement use the str_replace function from php it is much more effecient.

You should end up with this code to sanitize your input.
Code:

    $string = mysql_real_escape_string($string);
    $badWords = //This is just swear words and SQL terms
    $string = str_replace($badWords, "", $string);
    $string = htmlentities($string, ENT_QUOTES)


I hope I was of help.
oly0015
Thanks for the help, hopefully that will at least kill off any amateurs that try to break the system. When I get more of the system setup I'll most likely just use a rich text box system.
coreymanshack
oly0015 wrote:
Thanks for the help, hopefully that will at least kill off any amateurs that try to break the system. When I get more of the system setup I'll most likely just use a rich text box system.


No problem, if you need anything else post and I'll try to answer.
Agent ME
coreymanshack wrote:
You also know if your host has magic quotes enabled by default or not, if you don't look in the phpinfo();
Most web hosts don't enable this by default. It is up to the programmer to sanitize the data correctly.
I doubt your host is using magic quotes, so remove that block of code.

Most places I've seen have it enabled, and it doesn't hurt to check to see if its on and remove it if need be.

There's no reason to use mysql_real_escape_string() unless you're inserting the string into a database right then. There's no reason to use htmlentities() unless you're displaying the string in an HTML or XML page right then. Only run the sanitizers you need for where you're putting the data, or else you end up with HTML character codes stored in places that aren't meant for HTML.

Here's some properly sanitized example code. In the php code for posting a message:
Code:
<?php
function remove_magic ($string)
{
   if(get_magic_quotes_gpc())
   {   $string = stripslashes($string);   }
   return $string;
}

// $post is the text the user inputs to the site exactly as they enter it.
$post = remove_magic($_POST['post']);

echo "Posting your message: " . htmlentities($post);

function insert_post_to_database($string)
{
   $query = "INSERT INTO comments (post) VALUES ('". mysql_real_escape_string($string) . "')";
   mysql_query($query);
}

$db_host="localhost";
$db_user="admin";
$db_pass="pass";
mysql_connect($db_host, $db_user, $db_pass);
mysql_select_db("test");

insert_post_to_database($post);

mysql_close()
?>

And for displaying comments later:
Code:
<?php
function read_posts_from_database()
{
   $query = "SELECT post FROM comments";
   $result = mysql_query($query);

   $all_posts = array();

   $numrows = mysql_num_rows($result);
   for($i=0; $i<$numrows; $i++)
   {   $all_posts[$i] = mysql_fetch_row($result)[0];   }

   return $all_posts;   // array with all posts
}

$db_host="localhost";
$db_user="admin";
$db_pass="pass";
mysql_connect($db_host, $db_user, $db_pass);
mysql_select_db("test");

$posts = read_posts_from_database();

mysql_close();

foreach($posts as $post)
{
echo "<div class=\"post\">\n";
echo htmlentities($post);
echo "</div>\n";
}

?>

Notice that remove_magic() is only ran on strings immediately as they are read from $_POST (or $_GET). Note that htmlentities() is only ran on a string as it's about to be displayed in HTML. Note that mysql_real_escape_string() is only ran on a string as it's about to be entered into a MySQL database. There is no need to run extra sanitizers.

Errors in using sanitizing functions is the reason for most SQL injection hacks, and errors such as in forums that like to throw random \ in front of symbols. It's kinda amusing when I see a website that has a username botched up as "O\'hare" (caused by addslashes being run in the wrong place), "M&amp;M chocolate lover" (caused by htmlentities being run in the wrong place), etc.
coreymanshack
Agent ME wrote:
coreymanshack wrote:
You also know if your host has magic quotes enabled by default or not, if you don't look in the phpinfo();
Most web hosts don't enable this by default. It is up to the programmer to sanitize the data correctly.
I doubt your host is using magic quotes, so remove that block of code.

Most places I've seen have it enabled, and it doesn't hurt to check to see if its on and remove it if need be.

There's no reason to use mysql_real_escape_string() unless you're inserting the string into a database right then. There's no reason to use htmlentities() unless you're displaying the string in an HTML or XML page right then. Only run the sanitizers you need for where you're putting the data, or else you end up with HTML character codes stored in places that aren't meant for HTML.

Here's some properly sanitized example code. In the php code for posting a message:
Code:
<?php
function remove_magic ($string)
{
   if(get_magic_quotes_gpc())
   {   $string = stripslashes($string);   }
   return $string;
}

// $post is the text the user inputs to the site exactly as they enter it.
$post = remove_magic($_POST['post']);

echo "Posting your message: " . htmlentities($post);

function insert_post_to_database($string)
{
   $query = "INSERT INTO comments (post) VALUES ('". mysql_real_escape_string($string) . "')";
   mysql_query($query);
}

$db_host="localhost";
$db_user="admin";
$db_pass="pass";
mysql_connect($db_host, $db_user, $db_pass);
mysql_select_db("test");

insert_post_to_database($post);

mysql_close()
?>

And for displaying comments later:
Code:
<?php
function read_posts_from_database()
{
   $query = "SELECT post FROM comments";
   $result = mysql_query($query);

   $all_posts = array();

   $numrows = mysql_num_rows($result);
   for($i=0; $i<$numrows; $i++)
   {   $all_posts[$i] = mysql_fetch_row($result)[0];   }

   return $all_posts;   // array with all posts
}

$db_host="localhost";
$db_user="admin";
$db_pass="pass";
mysql_connect($db_host, $db_user, $db_pass);
mysql_select_db("test");

$posts = read_posts_from_database();

mysql_close();

foreach($posts as $post)
{
echo "<div class=\"post\">\n";
echo htmlentities($post);
echo "</div>\n";
}

?>

Notice that remove_magic() is only ran on strings immediately as they are read from $_POST (or $_GET). Note that htmlentities() is only ran on a string as it's about to be displayed in HTML. Note that mysql_real_escape_string() is only ran on a string as it's about to be entered into a MySQL database. There is no need to run extra sanitizers.

Errors in using sanitizing functions is the reason for most SQL injection hacks, and errors such as in forums that like to throw random \ in front of symbols. It's kinda amusing when I see a website that has a username botched up as "O\'hare" (caused by addslashes being run in the wrong place), "M&amp;M chocolate lover" (caused by htmlentities being run in the wrong place), etc.



..... what would be the purpose of sanitizing if you weren't going to put it in a databse......

Shocked
rvec
cross site scripting attacks in comments, mails, messages (maybe even error messages), ...
Sometimes people use eval or dynamic includes, those need to be sanitized as well.

In short; don't trust any user.
Agent ME
coreymanshack wrote:
..... what would be the purpose of sanitizing if you weren't going to put it in a databse......

Shocked

That's my point, your example code sanitized it without having some immediate purpose. You also ran htmlentities() on it before entering it into the database. Ideally, that should be done when you read the data out of the database and output it into HTML instead.

This point isn't too critical in strictly HTML systems, but say your application read out of the database for other uses too. Maybe you generate images from data in the database. When you read the data out of the database, ideally you just simply don't run htmlentities() on it because it's only needed for HTML output.

But if you run htmlentities() on it before it's even entered in the database, you've just over-sanitized. When a user tries to input "Café & Bar", the text "Caf&Atilde;&copy; &amp; Bar" is entered into the database. When this is read back into HTML, the browser interprets it right, but the simple image-generator will just give that text back.
coreymanshack
Agent ME wrote:
coreymanshack wrote:
..... what would be the purpose of sanitizing if you weren't going to put it in a databse......

Shocked

That's my point, your example code sanitized it without having some immediate purpose. You also ran htmlentities() on it before entering it into the database. Ideally, that should be done when you read the data out of the database and output it into HTML instead.

This point isn't too critical in strictly HTML systems, but say your application read out of the database for other uses too. Maybe you generate images from data in the database. When you read the data out of the database, ideally you just simply don't run htmlentities() on it because it's only needed for HTML output.

But if you run htmlentities() on it before it's even entered in the database, you've just over-sanitized. When a user tries to input "Café & Bar", the text "Caf&Atilde;&copy; &amp; Bar" is entered into the database. When this is read back into HTML, the browser interprets it right, but the simple image-generator will just give that text back.


I was under the impression they wanted to sanitize their results to put them in a DB. They asked about sanitizing.
Aredon
Quote:

I was under the impression they wanted to sanitize their results to put them in a DB. They asked about sanitizing.

Yeah I thought that too, and I was going to say that removing the mysql_real_escape_string() might not be a good idea. However, if it's not going into a database... I guess there's no worry about sql injections... Then again though, how are you going to store your guestbook if not for a database entry?
oly0015
So... for the last few posts to explain my thinking about the site.

You enter your name and message into two textboxes and hit submit. After this point it reloads the same page from the submit, it then grabs the data and cleans it then saves it into a SQL table. After that it uses the data by displaying a line as a subtitle on every page and it lists all of the entries on the about page. At this point I think I got it working good, has not messed up yet for all that I tried.

Sorry about not commenting on this earlier but I ran into a bit of a problem. I was using a wamp server as a testing platform and my computer bugged out, now I'm not sure if its the server or the code but I am getting a redirect for every link I go to where it adds this code on every address only in firefox. Trying to put it up on frihost for the moment just to see if its the server because the code was not doing this before the computer problem.

http://localhost/?oauth_consumer_key=d2pjcndnfg7wpysf2vkmvg8c%20&oauth_timestamp=1256578235&oauth_nonce=VmmbTs&oauth_signature_method=HMAC-SHA1&oauth_signature=pxhdBwomFhYrfI0Cmuq3zZQbTlE%3D
coreymanshack
oly0015 wrote:
So... for the last few posts to explain my thinking about the site.

You enter your name and message into two textboxes and hit submit. After this point it reloads the same page from the submit, it then grabs the data and cleans it then saves it into a SQL table. After that it uses the data by displaying a line as a subtitle on every page and it lists all of the entries on the about page. At this point I think I got it working good, has not messed up yet for all that I tried.

Sorry about not commenting on this earlier but I ran into a bit of a problem. I was using a wamp server as a testing platform and my computer bugged out, now I'm not sure if its the server or the code but I am getting a redirect for every link I go to where it adds this code on every address only in firefox. Trying to put it up on frihost for the moment just to see if its the server because the code was not doing this before the computer problem.

http://localhost/?oauth_consumer_key=d2pjcndnfg7wpysf2vkmvg8c%20&oauth_timestamp=1256578235&oauth_nonce=VmmbTs&oauth_signature_method=HMAC-SHA1&oauth_signature=pxhdBwomFhYrfI0Cmuq3zZQbTlE%3D



use xampp, sounds like the config you are using in apache.

unless these are GET variables you are using in PHP... GET are passed through the URL
oly0015
Yea I'm pretty sure if I do a reinstall it'll be fine, just a bit busy today atm..
Related topics
Flash login form?
Forms in Flash
Help with php email
How to: Make text inputs safe?
How to Input Text into a php script
Brownian Motion Smoke Simulation
php msql quiz script
Make Chrome stop adding padding space around my text boxes?
Visual Basic Tutorial - Control Arrays: What, Why and How
having text placed in a text field
Need a POLL - 45frih$'s!
HTML Tutorial.
Newb flash and xml question
highlighted text boxes
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.