Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

How to sanatize and validate form input.

Featured Replies

Hello, thought i would start a new thread, as my issue for a previous one was sorted.

 

Okay, so im trying to make a form that writes to a database secure and also use some if statements to allow it to write to a database / return false.

 

Okay, so heres the basic code:

 


<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }

mysql_select_db("database", $con);

$Suggestion = $_POST['Suggestion'];
$Email = $_POST['Email'];

$sql="INSERT INTO tablename (Suggestion, Email)
VALUES
('$_POST[suggestion]','$_POST[Email]')";

if (!mysql_query($sql,$con))
 {
 die('Error: ' . mysql_error());
 }
echo "Suggestion Added!";

mysql_close($con)
?>

 

So i have searched the web for an hour and haven't found what im looking for / cant understand it.

 

How do i go about only writing to the database IF the suggestion field is not empty, and the email is valid.

 

Then how do i go about sanatizing this data?

 

Just looking for some body to write a quick example based on my code so that i can understand it more!

 

Thanks for any replies, craig.

  • Author

Okay, latest attempt just from the top of my head... i only know if statements from java, so not sure if they relate the same...

 


//CHECK FOR EMPTY FIELDS
//------------------------------------------------

if(empty($_POST["Suggestion"]))
 	{
 echo "Suggestion field cannot be empty.<br/>";
 	}

if(empty($_POST["Email"]))
 	{
 echo "Email field cannot be empty.";
	}

//IF FIELDS ARE NOT EMPTY, PROCEDE TO INSERT
//------------------------------------------------

if(!empty($_POST["Suggestion"])) && (!empty($_POST["Email"]))
{
$sql="INSERT INTO suggestions (Suggestion, Email)
VALUES
('$_POST[suggestion]','$_POST[Email]')";

echo "Suggestion Added!";
mysql_close($con)
 	}

 

The last part isnt working as im sure my syntax is off but it was a guess... but am i heading in the right direction for validating?

 

If fields are empty it works, just need to make it work when the fields arent empty :)

 

Not quite sure how to approach this though...

Edited by Lovelock

  • Author

EDIT: Got it working.

 

//CHECK FOR EMPTY FIELDS
//------------------------------------------------

if(empty($_POST["Suggestion"]))
 	{
 echo "Suggestion field cannot be empty.<br/>";
 	}

if(empty($_POST["Email"]))
 	{
 echo "Email field cannot be empty.";
	}

if (!empty($_POST["Suggestion"]) && (!empty($_POST["Email"])))

{
$sql="INSERT INTO suggestions (Suggestion, Email) VALUES ('$_POST[suggestion]','$_POST[Email]')";

if (!mysql_query($sql,$con))
 	{
 	die('Error: ' . mysql_error());
 	}

echo "Suggestion Added! <br/> Redirecting back to Vinyl Penguin.";
mysql_close($con);
}

 

Anything wrong with this code or can i accept it as working and move onto sanitization?

Edited by Lovelock

There's a few bits wrong with it, first thing I do is add a blanket sanitisation...

 

// Function to make general data safe
function clean($string_name)
{
if (get_magic_quotes_gpc())
{
	$string_name = stripslashes($string_name);						// strip slashes if magic_quotes is on
}
$string_name = trim($string_name);									// Trim empty space before and after
if (function_exists("mysql_real_escape_string"))
{
	$string_name = mysql_real_escape_string($string_name);		// mysql_real_escape_string
}
else
{
	$string_name = addslashes($string_name);
}

return $string_name;
}

// Function to sanitize email data from form
function clean_email($string_email)
{
if (get_magic_quotes_gpc())
{
	$string_email = stripslashes($string_email);								// Add slashes
}
$string_email = filter_var($string_email, FILTER_SANITIZE_EMAIL);				// Sanitize email data
$string_email = trim($string_email);											// Trim empty space before and after
if (function_exists("mysql_real_escape_string"))
{
	$string_email = mysql_real_escape_string($string_email);					// mysql_real_escape_string
}
else
{
	$string_email = addslashes($string_email);
}
return $string_email;
}


// Now you can clean all your input for the database
$Suggestion = clean($_POST['Suggestion']);
$Email = clean_email($_POST['email']);

if (empty($Suggestion)) {
    //use die to end the script otherwise it will carry on
    die('Suggestion box can not be empty');
}
if (empty($Email)) {
    die('Email can not be empty');
}

// This checks the email is valid
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
    die('Not a valid email');
}


//Now insert the clean data
       $sql="INSERT INTO suggestions (Suggestion, Email) VALUES ('$Suggestion','$Email')";

       if (!mysql_query($sql,$con))
       {
       die('Error: ' . mysql_error());
       }

       echo "Suggestion Added! <br/> Redirecting back to Vinyl Penguin.";
       mysql_close($con);


 

That should make it at least safe to insert into your database and does a few checks for you, obviously you can go into a lot more detail but this should get you on your way.

Edited by adamsmith

  • Author

Thanks for the reply, i was just testing this and works fine:

 

//Sanatized Data
//-----------------------------------------------------

$Suggestion = mysql_real_escape_string($_POST['Suggestion']);
$Email = mysql_real_escape_string($_POST['Email']);

//Email Validation Check Function
//-----------------------------------------------------

function check_email_address($email) {
   // First, we check that there's one @ symbol, and that the lengths are right
   if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
       // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
       return false;
   }
   // Split it into sections to make life easier
   $email_array = explode("@", $email);
   $local_array = explode(".", $email_array[0]);
   for ($i = 0; $i < sizeof($local_array); $i++) {
        if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
           return false;
       }
   }    
   if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
       $domain_array = explode(".", $email_array[1]);
       if (sizeof($domain_array) < 2) {
               return false; // Not enough parts to domain
       }
       for ($i = 0; $i < sizeof($domain_array); $i++) {
           if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
               return false;
           }
       }
   }
   return true;
}

//Validation Checks
//-----------------------------------------------------

if(empty($_POST["Suggestion"]))
 	{
 echo "Suggestion field cannot be empty.<br/>";
 	}

if(empty($_POST["Email"]))
 	{
 echo "Email field cannot be empty.";
	}

if (check_email_address($Email)) {
} else {
   echo $Email . ' is not a valid email address.';
}

if (!empty($_POST["Suggestion"]) && (!empty($_POST["Email"]) && (check_email_address($Email))))

{
$sql="INSERT INTO suggestions (Suggestion, Email) VALUES ('$_POST[suggestion]','$_POST[Email]')";

if (!mysql_query($sql,$con))
 	{
 	die('Error: ' . mysql_error());
 	}

echo "Suggestion Added! <br/> Redirecting back to Vinyl Penguin.";
mysql_close($con);
}

 

For knowledge purposes, whats the difference between this and what you done? Is yours best to use etc?

 

Doesnt need an answer, but would be nice to expand my knowledge on what to use and what not to!

where you have used mysql_real_escape_string, I would use the function I made to sanitise general data instead as it checks that magic_quotes is off, if not this can lead to double escaping and can open your script up to sql injection.

 

Also, after you have sanitised the data you should use that new $variable for the rest of your script, for instance you have sanitised and escaped the $_POST data first, but then in the rest of your script you are still checking against the un-sanitised data, you are even inserting the un-sanitised data into your database so it doesn't even matter that you sanitised it in the first place.

 

To sanitised and validate the email, I would say to use the filter_var method instead of ereg as it should be faster and you know it works properly how you want it to.

where you have used mysql_real_escape_string, I would use the function I made to sanitise general data instead as it checks that magic_quotes is off, if not this can lead to double escaping and can open your script up to sql injection.

 

Also, after you have sanitised the data you should use that new $variable for the rest of your script, for instance you have sanitised and escaped the $_POST data first, but then in the rest of your script you are still checking against the un-sanitised data, you are even inserting the un-sanitised data into your database so it doesn't even matter that you sanitised it in the first place.

 

To sanitised and validate the email, I would say to use the filter_var method instead of ereg as it should be faster and you know it works properly how you want it to.

i'd also like to add use mysqli or PDO instead of the old mysql lib this is no longer kept updated as its part of PHP 4

  • Author

Okay, so im wanting to run the php on the same page as the form now.

 

I know how to make the form run on the same page.

 

But how do i stop the php from working as soon as the page is loaded and only on the form submit?

 

I tried for example:

 

if (isset($_POST['Submit']) && (empty($Suggestion))) {
    //use die to end the script otherwise it will carry on
    die('Suggestion box can not be empty');
}

 

I added the isset check and it doesnt show any error when page is loaded, but it also doesnt show anything when the form is submitted... what have i done wrong now :)?

 

Do i have to put a isset condition across the whole php code somehow?

 

EDIT: Bingo, worked easier than i thought it would wrapping the whole thing in an if statement haha.

 

One last, how do i go about putting the die message into a div?

 

for an echo i use this:

 

echo '<div id="submitmessage">', "Success! Suggestion Sent.", '</div>'; 

 

but cant get it to work with the die message...?

Edited by Lovelock

so basically your code should be something like this...

 

<?php
if (isset($_POST['submit'])) {
    // all the code goes here

    // This goes after the sql insert, it checks if the data was inserted into the database
    if((mysql_affected_rows()) == '1' ) {
         echo "<div id='submitmessage'>Success! Suggestion Sent.</div>";
    }
    else {
         echo "<div id='submitmessage'>Sorry, there was a problem submitting your form</div>";
    }
} //end isset
?>

<html>
...
</html>

 

I think you had your quotes the wrong way round, single quotes should go inside double quotes

Edited by adamsmith

Your full code will be something like this...

 

<?php
if (isset($_POST['submit'])) {

    // Function to make general data safe
function clean($string_name)
{
       if (get_magic_quotes_gpc())
       {
               $string_name = stripslashes($string_name);                                              // strip slashes if magic_quotes is on
       }
       $string_name = trim($string_name);                                                                      // Trim empty space before and after
       if (function_exists("mysql_real_escape_string"))
       {
               $string_name = mysql_real_escape_string($string_name);          // mysql_real_escape_string
       }
       else
       {
               $string_name = addslashes($string_name);
       }

       return $string_name;
}

// Function to sanitize email data from form
function clean_email($string_email)
{
       if (get_magic_quotes_gpc())
       {
               $string_email = stripslashes($string_email);                                                            // Add slashes
       }
       $string_email = filter_var($string_email, FILTER_SANITIZE_EMAIL);                               // Sanitize email data
       $string_email = trim($string_email);                                                                                    // Trim empty space before and after
       if (function_exists("mysql_real_escape_string"))
       {
               $string_email = mysql_real_escape_string($string_email);                                        // mysql_real_escape_string
       }
       else
       {
               $string_email = addslashes($string_email);
       }
       return $string_email;
}


// Now you can clean all your input for the database
$Suggestion = clean($_POST['Suggestion']);
$Email = clean_email($_POST['email']);

if (empty($Suggestion)) {
    //use die to end the script otherwise it will carry on
    die('Suggestion box can not be empty');
}
if (empty($Email)) {
    die('Email can not be empty');
}

// This checks the email is valid
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
    die('Not a valid email');
}


//Now insert the clean data
       $sql="INSERT INTO suggestions (Suggestion, Email) VALUES ('$Suggestion','$Email')";


    // This goes after the sql insert, it checks if the data was inserted into the database
    if((mysql_affected_rows()) == '1' ) {
         $success = "<div id='submitmessage'>Success! Suggestion Sent.</div>";
    }
    else {
         $success =  "<div id='submitmessage'>Sorry, there was a problem submitting your form</div>";
    }
} //end isset
?>

<html>
<head>
</head>
<body>
<?php
if (isset($success)) {
    echo $success;
}
?>
<body>
</html>

Edited by adamsmith

  • Author

this works for me just fine:

 

if (empty($Suggestion)) {
     echo '<div id="errormessage">', "Suggestion box cannot be empty. Please fill in.", '</div>';
}

if (empty($Email)) {
     echo '<div id="errormessage">', "Email box cannot be empty. Please fill in.", '</div>';
}

// This checks the email is valid
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
     echo '<div id="errormessage">', "$Email is not a valid email, please correct any errors.", '</div>'; 
}


//Now insert the clean data

if (!empty($Suggestion) && (!empty($Email) && (filter_var($Email, FILTER_VALIDATE_EMAIL)))) {

       $sql="INSERT INTO suggestions (Suggestion, Email) VALUES ('$Suggestion','$Email')";

       if (!mysql_query($sql,$con))
       {
       die('Error: ' . mysql_error());
       }

       echo '<div id="successmessage">', "Success! Suggestion Sent.", '</div>'; 
       mysql_close($con);

       }
       }

 

Instead of using the die, ive checked for no errors and only then will it input to the database.

 

Proabably not the most efficient way of doing it, but it works... question is... anything wrong with it?

this works for me just fine:

 

if (empty($Suggestion)) {
     echo '<div id="errormessage">', "Suggestion box cannot be empty. Please fill in.", '</div>';
}

if (empty($Email)) {
     echo '<div id="errormessage">', "Email box cannot be empty. Please fill in.", '</div>';
}

// This checks the email is valid
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
     echo '<div id="errormessage">', "$Email is not a valid email, please correct any errors.", '</div>'; 
}


//Now insert the clean data

if (!empty($Suggestion) && (!empty($Email) && (filter_var($Email, FILTER_VALIDATE_EMAIL)))) {

       $sql="INSERT INTO suggestions (Suggestion, Email) VALUES ('$Suggestion','$Email')";

       if (!mysql_query($sql,$con))
       {
       die('Error: ' . mysql_error());
       }

       echo '<div id="successmessage">', "Success! Suggestion Sent.", '</div>'; 
       mysql_close($con);

       }
       }

 

Instead of using the die, ive checked for no errors and only then will it input to the database.

 

Proabably not the most efficient way of doing it, but it works... question is... anything wrong with it?

 

I don't see anything technically wrong with it, granted it's not exactly how I would do it, but it should generate similar results

Edited by adamsmith

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.