HTML Text Field Validation

Jawwe23
Jawwe23 used Ask the Experts™
on
Hello,

    I have a webpage which contains multiple text fields with data being stored into a MySQL database. My issue is that I have a "first name" text field and am looking for a way to validate that it does not contain any malicious code that might cause a MySQL injection. Although Spry validation works well for my "e-mail" and "phone number" fields, when it comes to a "first name" field it is only able to validate that a value has been entered. Although Spry patterns may be set to filter out unwanted characters, as far as I'm aware such patterns may only be set on values that have a pre-determined length. Since there is not pre-determined exact length of any user's name, Spry is not able to help me identify (or block) characters that are part of any potential malicious code that might cause a MySQL injection.

    From reading several other articles on here, it seems that this type of security check on the "first name" text field value may be performed by using Javascript - although an expert on this site recently warned me about relying on Javascript since not all users may have it enabled in their browser.

    So.... I'm a bit lost.

    My request is two-fold:

    1. Is using Javascript really the best way to analyze a value in a "first name" text field to identify hazardous characters (characters not needed for entering a name) to ensure protection from MySQL injection? If not, what is?

    2. Although I see many examples of code on this site, I would appreciate if someone could locate the code (Javascript or otherwise) that I would need. There seem to be many variations of the code and I want to be sure I will be using the code that is most proper for my situation. While I do not know the exact characters which the code should be looking to block, I'd imagine there must be some sort of standard which would allow all letters and common name punctuation such as hyphens, commas, and apostrophes.

     Thanks in advance!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Haroon Ur RashidSr. Software Engineer

Commented:
Jawwe23, these are two different things, you can use javascript for validation of user inputs and php to stop sql injection.
PHP: mysql_real_escape_string (your string);
Javascript:
function check(){
if (document.formname.first_name.value=="")
{
alert("please complete this form!")
return false
}
} etc

Author

Commented:
Hello Haroon-Rashid,

      I would like to clarify your response - please let me know if I am not understanding:

1. Javascript wouldn't make any adjustment to any value, it would simply prevent the value from being submitted.

2. As such Javascript does not have to be used and instead a PHP command may be utilized to strip a potentially malicious submitted value of characters which would not likely be appropriate to include in a name text field?
Haroon Ur RashidSr. Software Engineer

Commented:

thanks Jawwe23, for simple way in which you explain the things. Yes i was totally agree with it. and if you need any tested framework for this, i will be happy to provide u. :)
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
Thank you for your quick response Haroon-Rashid. I am looking for some further help to understand how to implement your advice in your original post.

- - - -

I have two PHP pages. On page1.php, the user has to complete two text fields: one for their first name and another for their last name. The values entered are sent to page2.php via the following command:      

<form method="post" action="page2.php">

- - - -

On page2.php, I run each of the values through an encrypt function:

$firstname=encrypt($_POST['firstname'], $key);
$lastname=encrypt($_POST['lastname'], $key);

At the bottom of page2.php there is a submit button which runs the following code:

if ($submit)
{
mysql_query("INSERT INTO `database` (firstname, lastname) VALUES ($firstname, $lastname)
}

- - - -

On page1.php, I think it makes sense to leave the Spry validation on the first and last name text fields; at least it will ensure that a value is successfully entered - even if it is malicious.

On page2.php, I would like to use your PHP code to ensure that SQL injection does not take place. How would I accomplish this? I assume that I would have to do this before I attempt to encrypt it.

$firstname = mysql_real_escape_string($_POST['firstname']);

 // takes variable from page1.php and strips it of any inappropriate characters

THEN

$FINALfirstname = encrypt($firstname, $key);

// takes the "cleaned" variable and now runs it through the encrypt function

- - - -

Is this correct?

Thank you for your time!
Hi,

You can see the following sample in snippet.

Regards,
<html>
<head>
<script type="text/javascript">
function validate_email(field,alerttxt)
{
with (field)
  {
  apos=value.indexOf("@");
  dotpos=value.lastIndexOf(".");
  if (apos<1||dotpos-apos<2)
    {alert(alerttxt);return false;}
  else {return true;}
  }
}
 
function validate_form(thisform)
{
with (thisform)
  {
  if (validate_email(email,"Not a valid e-mail address!")==false)
    {email.focus();return false;}
  }
}
</script>
</head>
 
<body>
<form action="submit.htm" onsubmit="return validate_form(this);" method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>
 
</html>

Open in new window

Author

Commented:
Hello Sokharolt,

     It is not the e-mail address field that I am concerned about as I already have Spry working to validate that. I am concerned about users being able to enter in malicious code into a "first name" field and potentially inject into the MySQL database. Your script seems to do essentially what my Spry is already doing for my e-mail text field (unless I am not understanding your code).
     I am looking for a way to strip the "first name" variable of any potential hazardous characters so that any value entered into the database is safe.
Haroon Ur RashidSr. Software Engineer

Commented:
yes, you flow is totaly correct and most of the developer follow this way. :)

Author

Commented:
Haroon-Rashid:

    I ran some tests using the "PHP: mysql_real_escape_string (your string);" code you provided.

Here's what I came up with:

// * * * * * * * *

function safe($value)
{    
return mysql_real_escape_string($value);
}
 
$fname = safe($_POST['firstname']);

// * * * * * * * * *


     In this test, I did not apply any encryption - only the safe function to ensure that any bad user-entered data would be filtered before being inserted into the database.

    During my first test, I pretended to be a user and entered my first name as:  OR 12 = 1    . I looked in the database and this was the code that was actually stored as â¬Ü OR â¬Ü1⬲ = â¬Ü1  . Since this was different than the code I had entered, I believed that the safe function actually worked.

    During my second test, I removed the safe function so that the user-entered information would be stored into the SQL database with no protection. (only $fname = $_POST['fname'];) When I completed the form again using the same 'OR '1' = '1 as my first name, I noticed the database stored the information with the same exact value as the first time, â¬Ü OR â¬Ü1⬲ = â¬Ü1.

    As such, I'm a bit confused. It seems as if the mysql_real_escape_string isn't doing anything - or perhaps the SQL database is doing some sort of filtering of it's own?

    Can you help explain to me why the data stored in both cases is exactly the same? Point value has been increased.

 
Haroon Ur RashidSr. Software Engineer

Commented:
thats good, to try this example but i like  to explain this function. mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.
please read this topic "Use this function to prevent database attack!". here you can also see such example and corective way. ihope its work for u. thanks
http://www.w3schools.com/PHP/func_mysql_real_escape_string.asp
 
Sr. Software Engineer
Commented:
following are the complete function which u may use.

function check_input($value)
{
     // Stripslashes
     if (get_magic_quotes_gpc()) {
        $value = stripslashes($value);
     }
 
     // Quote if not a number
     if (!is_numeric($value)) {
        $value = "'" . mysql_real_escape_string($value) . "'";
     }
 
     return $value;
 
}

Open in new window

Author

Commented:
Hello Haroon-Rashid,

      Thank you for your post. I have been quite busy with work but hope to be able to test out your code tomorrow. Thank you for your patience.

Author

Commented:
Hello Haroon-Rashid,

     I have been trying to test the code you provided from w3schools. The code, as used in their example, uses the function to check user-entered data to ensure it is safe before using it to select a row in a database. In my case, I am trying to check user-entered data in insert into a database. It is a little different, although I'm sure that it still should be checked/reviewed before being placed into the database.
     My issue is that when I do not use the function, the user-entered data is inserted into my database. When I use the function, absolutely nothing is inserted. I can't figure out why using the function is preventing any data from being written. Can you please take a look at my code?
 

     
<body>
<?php 
// Include code to connect to database 
// Get values from previous page's form 
$fname = $_POST['fname'];
echo "Before the function, my value is = " . $fname; 
function check_input($value)
{
     // Stripslashes
     if (get_magic_quotes_gpc()) {
        $value = stripslashes($value);
     }
 
     // Quote if not a number
     if (!is_numeric($value)) {
        $value = mysql_real_escape_string($value);
     }
 
     return $value; 
} 
// If I comment out the next two lines, the database writes the $fname value into the database. When I run $fname through the function below, nothing is recorded.  
$fname = check_input($fname);
echo "After the function, my value is now = " . $fname; 
mysql_query("INSERT INTO `database` (`fname`) VALUES ('$fname')"); 
?>
</body>
</html>

Open in new window

Author

Commented:
Hello Haroon-Rashid,

      Please disregard my previous post. I am preparing a new post for you in just a few moments. Thank you.

Author

Commented:
Hello,

    Here is my full code, as mentioned in my previous post, when I enter and submit a value, nothing is entered into the database - and I can not figure out why. Can you identify any issues?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="css/styles.css" type="text/css" media="screen, projection" charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled</title>
</head> 
<body> 
<?php 
// data removed for public posting
$host=""; // Host name 
$username=""; // Mysql username 
$password=""; // Mysql password 
$db_name=""; // Database name 
$tbl_name=""; // Table name  
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB"); 

// Get values from form
$fname = $_POST['fname'];
echo "Before the function, my value is = " . $fname; 
function check_input($value)
{
     // Stripslashes
     if (get_magic_quotes_gpc()) {
        $value = stripslashes($value);
     }
 
     // Quote if not a number
     if (!is_numeric($value)) {
        $value = "'" . mysql_real_escape_string($value) . "'";
     }
 
     return $value; 
} 
$fname = check_input($fname);
echo "After the function, my value is now = " . $fname; 
mysql_query("INSERT INTO `database` (`fname`) VALUES ('$fname')"); 
?>
</body>
</html>

Open in new window

Author

Commented:
One thing that I just noticed:

If I enter my fname as       '    

When it runs through the function and I echo the value, it shows up as    \'    I think this means that the function is working.

I logged into MySQL and manually tried to insert   \'   into the database and I noticed that it used the following code:   \\''    (two slashes and two single quotes) in order to store    \'

Is it possible that MySQL, when I enter it manually, knows to add the extra slash and extra quote ( \\'' ) to store the value (  \'  ) but when I try to do it through PHP, MySQL sees the (  \'  ) and just thinks it is garbage and doesn't add the extra slashes?

I have no idea. I'm quite confused.

Author

Commented:
I'm not sure of the solution but I'm really thinking that this is because w3schools is using this function to filter user data (not stored in the database) before they use it to run a MySQL command.

In my situation I'm trying to filter it before it is actually stored into the MySQL database.

There seems to be something going on where MySQL is doing some of it's own filtering, perhaps.

Using the code above, if I enter my fname as   \x00     the echo command shows     \\x00    which I believe is what you want. However, I look in my database and it is storing it as \x00 (without the second backslash).

I apologize for so many of the posts - but is anybody able to help me figure out what is going on?

When you are allowing a user to enter data to be stored into the database, isn't there any code that should be used to make sure they are just typing their name and nothing strange? Any code that just simply allows characters and no punctuation?

Author

Commented:
This function does seem to be one of the accepted ways to prevent a MySQL injection attack via text fields.

It doesn't seem to be the only way (nor the most absolute in security) but it seems to provide a good level of security for its ease-of-use.

I have another thread labeled "Understanding MySQL Injection - Is the MySQL INSERT Command considered a query in the same way as the SELECT Command?" which has provided additional insight to this solution as many of my follow-up questions went unanswered. I suggest searching for the above mentioned thread if you are looking for more detailed explanations.

Despite not responding to the follow up questions that I had, I still would like to thank Haroon-Rashid for pointing me in the right direction.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial