How To Sanitize & Validate User Inputs On These Types Of Inputs?

Hello,

How are you community ? I signup now.
I need to ask question. About User Input Sanitization. About Input Validation: Email, Domain, Url, Phone, Fax, Mobile, Zip.
So can someone teach me how to do all this ? I tried but no luck.
My attempt is fruitless …

<html>
<head>
<title>
Searchengine Result Page
</title>
</head>
<body>

<form method = 'POST' action = "$_SERVER['PHP_SELF']">
<label for='find'>Find</label>
<input type='text' name='find' id='find'>
<br>
Table:
<input type='radio' name='table' id='sale'><label for='table'>Businesses On Sale</label>
<input type='radio' name='table' id='sold'><label for='table'>Businesses Sold</label>
<br>
<label for='business_name'>Business Name</label>
<input type='text' name='business_name' id='business_name'>
<label for='business_zip'>Business Zip</label>
<input type='text' name='business_zip' id='business_zip'>
<label for='business_phone'>Business Phone</label>
<input type='text' name='business_phone' id='business_phone'>
<label for='business_mobile'>Business Mobile</label>
<input type='text' name='business_mobile' id='business_mobile'>
<label for='business_fax'>Business Fax</label>
<input type='text' name='business_fax' id='business_fax'>
<label for='business_email'>Business Email</label>
<input type='text' name='business_email' id='business_email'>
<label for='business_description'>Business Description</label>
<input type='text' name='business_description' id='business_description'>
<button type='submit'>Submit!</button>
</form>
</body>
</html>

<?php

//ERROR REPORTING FOR DEVMODE ONLY.
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);

//MYSQLI CONNECTION.
mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';

if(!$conn = mysqli_connect("$server","$user","$password","$database"))
{
	echo 'Mysqli Connection Error' .mysqli_connect_error($conn);
	echo 'Mysqli Connection Error Number' .mysqli_connect_errno($conn);
}

if(!mysqli_character_set_name($conn) == 'utf8mb4')
{
	echo 'Initial Character Set: ' .mysqli_character_set_name($conn);
	mysqli_set_charset("$conn",'utf8mb4');
	echo 'Current Character Set: ' .mysqli_character_set_name($conn);
}

//SANITIZE/VALIDATE USER INPUT
function test_input($data)
{
	$data = trim($data);
	$data = stripslashes($data); //Strips only Backward Slashes. Not Forward Slashes.
	//$data = htmlspecialchars($data);
	$data = strip_tags($data);
	
	return $data;
}

if(!empty(trim($_POST['business_name'])))
{
	$business_name = trim($_POST['business_name']);
	if(!is_string($business_name))
	{
		die('Enter Your Busieness Name! Can only contain Alpha-numerical Characters!');
	}
	$business_name = filter_var($business_name, FILTER_SANITIZE_STRING);
	if(!filter_var("$business_name", FILTER_VALIDATE_STRING))
	{
		die("Enter your valid Business Name!");
	}
}
elseif(!empty(trim($_POST['business_zip'])))
{	
	$business_zip = trim($_POST['business_zip']);
	if(!is_string($business_zip)||!is_int($business_zip))
	{
		die('Enter your Business Zip! Can only contain Alpha-numerical Characters!');
	}
	$business_zip = filter_var($business_zip, FILTER_SANITIZE_ZIP);
	if(!filter_var("$business_phone", FILTER_VALIDATE_ZIP))
	{
		die("Enter your valid Business Zip!");
	}
}
elseif(!empty(trim($_POST['business_phone'])))
{
	$business_phone = trim($_POST['business_phone']);
	if(!is_string($business_phone)||!is_int($business_phone))
	{
		die('Enter your Business Phone! Can only contain Alpha-numerical Characters!');
	}
	$business_phone = filter_var($business_phone, FILTER_SANITIZE_PHONE);
	if(!filter_var("$business_phone", FILTER_VALIDATE_PHONE))
	{
		die("Enter your valid Business Land-line Phone Number!");
	}
}
elseif(!empty(trim($_POST['business_mobile'])))
{
	$business_mobile = trim($_POST['business_mobile']);
	if(!is_string($business_mobile)||!is_int($business_mobile))
	{
		die('Enter your Business Zip! Can only contain Alpha-numerical Characters!');
	}
	$business_mobile = filter_var($business_mobile, FILTER_SANITIZE_MOBILE);
	if(!filter_var("$business_mobile", FILTER_VALIDATE_MOBILE))
	{
		die("Enter your valid Business Mobile Phone Number!");
	}
}
elseif(!empty(trim($_POST['business_fax'])))
{
	$business_fax = trim($_POST['business_fax']);
	if(!is_string($business_fax)||!is_int($business_fax))
	{
		die('Enter your Business Fax! Can only contain Alpha-numerical Characters!');
	}
	$business_fax = filter_var($business_fax, FILTER_SANITIZE_FAX);
	if(!filter_var("$business_fax", FILTER_VALIDATE_FAX))
	{
		die("Enter your valid Business Land-line Fax!");
	}
}
elseif(!empty(trim($_POST['business_email'])))
{
	$business_email = trim($_POST['business_email']);
	if(!is_string($business_email))
	{
		die('Enter your Business Email! Can only contain Alpha-numerical Characters!');
	}
	$business_email = filter_var($business_email, FILTER_SANITIZE_EMAIL);
	if(!filter_var("$business_email", FILTER_VALIDATE_EMAIL))
	{
		die('Enter your valid Business Email!');
	}
}
elseif(!empty(trim($_POST['business_domain'])))
{
	$business_domain = trim($_POST['business_domain']);
	if(!is_string($business_domain))
	{
		die('Enter your Business Domain! Can only contain Alpha-numerical Characters!');
	}
	$business_domain = filter_var($business_domain, FILTER_SANITIZE_DOMAIN);
	if(!filter_var("$business_domain", FILTER_VALIDATE_DOMAIN))
	{
		die("Enter your valid business website's Domain!");
	}
}
elseif(!empty(trim($_POST['business_url'])))
{
	$business_url = trim($_POST['business_url']);
	if(!is_string($business_url))
	{
		die('Enter your Business Url! Can only contain Alpha-numerical Characters!');
	}
	$business_url = filter_var($business_url, FILTER_SANITIZE_URL);
	
	if(!filter_var("$business_url", FILTER_VALIDATE_URL,FILTER_FLAG_SCHEME_REQUIRED))
	{
		die("Enter your valid Business website's full Url!");
	}
	elseif(!filter_var("$business_url", FILTER_VALIDATE_URL,FILTER_FLAG_HOST_REQUIRED))
	{
		die("Enter your valid Business website's full Url!");
	}
	if(!filter_var("$business_url", FILTER_VALIDATE_URL,FILTER_FLAG_PATH_REQUIRED))
	{
		die("Enter your valid Business website's full Absolute Url!");
	}
}
elseif(!empty(trim($_POST['business_description'])))
{
	$business_zip = trim($_POST['business_description']);
	if(!is_string($business_description))
	{
		die('Enter your Business Zip! Can only contain Alpha-numerical Characters!');
	}
	$business_description = filter_var($business_description, FILTER_SANITIZE_STRING);
	if(!filter_var("$business_description", FILTER_VALIDATE_STRING))
	{
		die("Enter your Business Description!");
	}
}
else
{
	//SUBMIT USER INPUT TO DB
	$sql = "INSERT into business_links (business_name,business_zip,business_phone,business_mobile,business_fax,business_email,business_domain,business_url,business_description) VALUES (?,?,?,?,?,?,?,?,?)";
	$stmt = mysqli_stmt_init($conn);
	if(mysqli_stmt_prepare($stmt,$sql))
	{
		mysqli_stmt_bind_param($stmt,'sssssssss',$business_name,$business_zip,$business_phone,$business_mobile,$business_fax,$business_email,$business_domain,$business_url,$business_description);
		if($result = mysqli_stmt_execute($stmt))
		{
			echo 'Submission Success!';		
			echo mysqli_stmt_affected_rows($stmt);
		}
		else
		{
			//Error Messages for Production Mode only.
			echo 'Submission Execution Failed!';
			echo 'Error: ' .mysqli_stmt_error($stmt);
			echo 'Error: ' .mysqli_stmt_errno($stmt);
			echo 'Entry Count: ' .mysqli_stmt_affected_rows($stmt);
		}
		mysqli_stmt_close($stmt);
	}
	else
	{
		//Error Messages for Production Mode only.
		echo 'Submission Preparation Failed!';
	}
	mysqli_close($conn);
}

?>

My issues:
1.
filter_var("$business_name", FILTER_VALIDATE_STRING)

filter_var($business_zip, FILTER_SANITIZE_ZIP);

filter_var("$business_phone", FILTER_VALIDATE_ZIP)

filter_var($business_phone, FILTER_SANITIZE_PHONE)

filter_var("$business_phone", FILTER_VALIDATE_PHONE)

filter_var($business_mobile, FILTER_SANITIZE_MOBILE)

filter_var("$business_mobile", FILTER_VALIDATE_MOBILE)

filter_var($business_fax, FILTER_SANITIZE_FAX)

filter_var("$business_fax", FILTER_VALIDATE_FAX)

filter_var($business_domain, FILTER_SANITIZE_DOMAIN)

filter_var("$business_domain", FILTER_VALIDATE_DOMAIN)

filter_var("$business_description", FILTER_VALIDATE_STRING)

Above functions invalid. No exist. Can you tell me of any substitutes ? I cant find none, myself. I give-up. I very tired now.
If no substitutes, then may we build our own custom functions ? I sure not know how to begin. Scratching my head.

Any sample codes welcome to get me on my way.

And, is my code ok with exception of my invented invalid php functions ?
In you opinion, can my code be much improved or little ?
Any serious mistakes on my programming ?
Is my code hacker proof ? Is my code safe ? I do not want users submitting malicious codes on my commenting section where when I display their submissions on my pages, I get my webpage html getting broken. Xss, Javascript attacks, etc.
That is my main aim for security fuss on my code. Ok ?

Thank you people for your volunteers.

Hello urgentenquirer,

Since this is a form, you want to be using filter_input and not filter_var. Since your form is also posting, you will want to use INPUT_POST with the filter_input.

So lets take the email textbox… which has a name business_email. You would use it like this…

$filtered_email = filter_input('INPUT_POST", 'business_email', FILTER_VALIDATE_EMAIL);

Here we are saying that we want to filter the input with the name of business_name and validate it for being an email address. Notice we are using a plain old string for the name, not a variable with a dollar sign. We just need the name of the field.

We also validate it for being an email. Meaning that if it is not an email, the filter fails and sets $filtered_email to false. If the field didn’t even exist in the form, then it would be NULL. Read more about it at https://www.php.net/manual/en/function.filter-input.php

If you do want to continue using filter_var then make sure you are putting in just the variable name, not inside quotation marks. In other words…

$filtered_email = filter_var($business_email, FILTER_VALIDATE_EMAIL);

Notice we are just putting the variable in there. Not inside quotes. That would make it a string. :slight_smile:

I hope you find this useful.

1 Like

It would help if you posted the exact error message you are receiving.

The filter extension, where filter_var() is defined, is a part of php’s core since php5.2. If it doesn’t exist, either you are using a very old version of php (you should always use the latest supported version), your php was built with the extension intentionally disabled (you would need to obtain a build with the extension or re-build it yourself), or there’s something going on with the character set in your code where filter_var isn’t being recognized by php (delete and re-type at least one of the instances to check.)

BTW - other than trimming data, mainly so that you can detect if all white-space characters were entered, you should NOT modify user submitted data. You should validate it and only use it if it is valid. If it is not valid, tell the user what was wrong with it. By modifying and blindly using the modified result, you have changed the meaning of the data and the user doesn’t know that you did it.

As to the actual code, about 25% of the typing is either unnecessary or isn’t doing what you think and should be redone. Here’s a run-down of the issues -

  1. Don’t use $_SERVER[‘PHP_SELF’] unless you apply htmlentities() to it to prevent cross site scripting, and in most cases there’s no need to use $_SERVER[‘PHP_SELF’] at all.
  2. To get a form to submit to the same page, leave the entire action=’…’ attribute out of the form tag.
  3. If you do want to use a php variable as the action attribute, you need to echo it in a php context. What you currently have is using the characters $, _, S, E, … as the action attribute value.
  4. A search form should be a get method form, since it determines what data will be gotten/produced and displayed on the page. A post method form is used when performing an action on the server, such as inserting, updating, or deleting data.
  5. Form fields should be ‘sticky’ and re-populate the fields with any existing data.
  6. If you are just starting out, start with one form field, then once you get all the logic to work the way you want, you can deal with the code needed for all the rest of the fields.
  7. Not sure if you just posted the code that way or if that’s how your code is arranged, but any php initialization, post method form processing, and the main get method logic should be above the start of the html document.
  8. Any php error related settings should be in the php.ini on your system so that you can change them at a single point without needing to find them in your code and edit your code. BTW - setting display_startup_errors in your code doesn’t work.
  9. Since you are using exceptions for msyqli database errors, you should remove ALL the existing mysqli error handling logic since it won’t get executed upon an error.
  10. If you switch to the much simpler PDO extension, about half of the php database statements will go away.
  11. Don’t use the root database user for your application. Create a specific user, with a password, that only has the permissions needed for your application.
  12. Don’t put quotes around php variables. This is just a waste of typing.
  13. Forget about this ridiculous test_input() function that came from w3schools. The only thing is is doing properly is trimming the data.
  14. Also forget about this repetitive conditional input logic that has you repeating yourself over an over. Instead, keep the input data as an array, then operate on elements in this array throughout the rest of the code. Keeping the data as an array will also lead to more advanced programming where you can dynamically validate and process the data without writing out code for every input.
  15. After you do item #14, you can trim all the input data at once, using one php array operation. You would then validate the trimmed data.
  16. is_string() tests the type of the variable, not the value in the variable, and by definition, all external $_POST, $_GET, $_COOKIE, … data are strings, regardless of what value is in the variable. Likewise, is_int() tests the type of the variable, not the value in the variable.
  17. You should use an array to hold validation/user error messages. You would then validate all the independent inputs at once, storing the validation error messages in the array, with the field name as the array index. This will let you remove all the die() statements and the elseif() logic for the independent inputs.
  18. As already mentioned above, don’t modify user data, therefore don’t use any of the SANITIZE filters.
  19. After the end of the validation logic, if there are no errors (the array holding the errors will be empty), use the submitted data.
  20. The ‘failure’ code for if/else logic is usually shorter than the ‘success’ code. If you reverse the if condition and put the shorter ‘failure’ code first, it will result in easier to read code.
  21. Upon successful completion of post method form processing code, you should execute a redirect to the exact same url of the current page to cause a get request for the page. This will prevent the browser from trying to re-submit the form data should you reload the page or browse away and back to the page. If you want to display a one time success message, store it in a session variable, then test, display, and clear the session variable at the appropriate location in the html document.
  22. There’s generally no need to close prepared statements, free results, or close database connections, since php will destroy all the resources on a page when your script ends.
  23. Any external, unknown, dynamic value that you output on a web page should have htmlentities() applied to it, right before you output it.
  24. //Error Messages for Production Mode only. Don’t have code that you will need to edit/remove when moving between different environments. For the case of database statements, using exceptions for errors and in most cases letting php catch the exception, will cause php to ‘automatically’ display/log the actual error information, the same as displaying/logging php errors. The exception to this rule is when inserting/updating user submitted data. In this case your code should catch the exception, detect if the error number is for a duplicate value, setup and display a message telling the user what was wrong with the data that they submitted. For all other error numbers, just re-throw the exception and let php handle it.
1 Like

Thread closed as the OP is banned.