the order of application of Sanitization, Escaping and Validation in php - php

I’m a beginner and trying to create a user registration form in php. After so much searching and reading (mostly here in stack overflow-the search was so intense - twice they asked me if I’m a robot) I came to know that I have to go through at least three (as far as I know) procedures before inserting the data in to the data base.
1.Sanitization
2.Escaping
3.Validation
My question is, what is the order of application of these procedures – which comes first and which one comes second and third.
For example I found this code online.
<?php
$emailErr = "";
$email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
They trim, remove back slashes and then replacing the html special characters before validate it with filter_var().
But I think the filter_var() should be the first to apply, is that right or I’m a stupid who doesn’t get it right ?
(By the way – as far as I know the backslashes are allowed in an email, if we use stripslashes() wouldn’t that be a problem too?)

Related

PHP single page form validation form not validating

Nothing happens when you click the submit button at the bottom of the page. I simply want it to validate user input and I am only focused on the name field at the moment and I cannot get it to validate any input in the name field. No error messages pop up or anything. Please review this and offer any suggestions, I cannot find my error.
PHP portion, where variables are initialized and set to empty. As well as the post methods and isset functions
<?php
//define variables and set them to empty values
$fname_error= $phone_error= $address1_error= $address2_error= $city_error= $state_error= $zipcode_error= "";
$fname= $phone= $address1= $address2= $city= $state= $zipcode= "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fname_error = "Missing";
}
else {
$fname = test_input($_POST["fname"]);
//now we check to see that the name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fname_error = "Please use letters and white space only";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The Html portion:
<div class="userinput">
<label for="fname"><b>First Name</b></label>
<input type="text" name="fname" value="<?php
echo $fname ?>">
<span class="error">
<?php echo $fname_error;?></span>
</div>
Good day. This is just a hypothesis, I may be wrong as I couldn't check the entire code, but you cannot have more than 1 form on the same page. Because, you need a single opening and closing form tag that wraps ALL form elements on your page. Form fields are only counted as part of a form if they are contained within the form elements. And you do have more than 1 form on the same page.
Also, you should consider minimizing your code to only what's needed.
Hope this helps!!!

PHP Form sends Email even if Email and Name are invalid

Hi everyone and thanks for your time!
Although it's the first time that I try PHP, I've been making a PHP Form and so far I've been able to make it validate the fields, and also that the form doesn't send anything if the fields are empty.
Now... The fields "Name" and "Email" have validation filters...
"Name" doesn't allow more than "letters and white spaces" and "Email" doesn't allow an "invalid Email format".
Example:
Name: Rob3rt... it has a number
Email: anything... isn't an Email address
Subject and Message have no validation filters...
The problem is, that if I fill up all fields, the form sends the Email, even if the information written on "Name" and "Email" doesn't agree with their validation filters...
Q: How can I hold the form from sending an Email, until all fields have the correct information inside?
Here's the code:
// This is the validation code //
<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = $subjectErr = "";
$name = $email = $comment = $subject = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "<h5>Name is required</h5>";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "<h5>Only letters and white space allowed</h5>";
}
}
if (empty($_POST["email"])) {
$emailErr = "<h5>Email is required</h5>";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "<h5>Invalid email format</h5>";
}
}
if (empty($_POST["comment"])) {
$commentErr = "<h5>Message is required</h5>";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["subject"])) {
$subjectErr = "<h5>Subject is required</h5>";
} else {
$subject = test_input($_POST["subject"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form>
Form comes here
</form>
// This is the sending code... I think the problem is here... //
<?php
if($_POST['name']!="" && $_POST['email']!="" && $_POST['comment']!="" && $_POST['subject']!="") {
$to = "myemail#whatever.com";
$email = "From: " . $email . "\r\n";
$subject = "" . $subject . "\r\n";
$comment = "" . $comment . "\r\n";
mail($to,$subject,$comment,$email);
echo "good";
}
else {
"bad";
}
?>
It is not working, because you never check if an error occurred, you are only checking if the fields are not empty before you send the mail.
The simplest way to fix it is replacing
if($_POST['name']!="" && $_POST['email']!="" && $_POST['comment']!="" && $_POST['subject']!="") {
with
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $nameErr === '' && $emailErr === '' && $commentErr === '' && $subjectErr === '') {
There is no no need to check for empty fields again, you have already done it before, so you just need to check if you are POSTing the form and if all errors are empty.
Some advice on how to generally improve your code:
1) Do not handle the HTTP POST in two positions (once above the form and once below). Merge it together in one PHP code block.
2) At least make sure that the user can't re-submit a successful form by reloading the site. After a successful submit, redirect the page. Something like this:
mail($to,$subject,$comment,$email);
header('Location:' . $_SERVER['REQUEST_URI'] . '?status=ok');
exit();
3) separate your HTML from your PHP or you will end up with a huge file which gets hard to maintain. Put your HTML form in a separate file and include it.
Although imho the nicest solution for a form is to sanitize in in JavaScript, submit it via AJAX (with angular, react, jQuery, whatever), handle it (and sanitize the data again) in PHP, send a 4xx HTTP header on error and return the error messages as a JSON object, which you then use in JavaScript.

How to prevent a script from running when email does not pass filter_var

I'm trying to make the emails pass validation by using filter_var. However, I am not sure how to prevent the script from processing the form data to my database if the email is not valid.
I have
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
exit();
}
the email obviously comes from what was entered in by the user and is in the $_POST variable. The script DOES show the email as valid or invalid, however it STILL processes the script and places the form data into my database. I thought that putting "exit()" would be the solution to this, or the proper way to handle when it's not valid. It simply opens a new page where the echo print shows.
What am I missing or doing wrong? Ideally I would like the form field to highlight and give the user some indication that they've entered in an incorrectly formatted email address (although I know that is a different topic and somewhat a bells and whistles type of thing), but I certainly do not want to allow the script to process the data into my database.
The answer lies in where the validation code was placed. Instead of placing it RIGHT AFTER the posted variables and before the SQL insertion code, I put it at the very end of the script. So the posted data went into the database before they can be validated.
So now, I have (which works)
$name = $_POST['name'];
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is not a valid email address");
exit();
} else {
$msg_to_user = '<br /><br /><h4>Thanks ' . $name . ', we will send you news when appropriate. Take care!</font></h4>';
$name = "";
$email = "";
}
// THE SQL SELECT STATEMENT TO ENSURE NO DUPLICATE EMAIL AND THEN THE INSERT STATEMENT TO PUT THE DATA IN THE DATABASE COMES AFTER THE CODE ABOVE

How can i use validate my signup form in php

I want to check all my signup fiels to be validate in php but it seems it not take other validation except email validation. Please have a look so that can help me to bug my errors.
Thank you.
Here its my signup process...
if($_POST['action']=="signup")
{
$name = mysqli_real_escape_string($connection,$_POST['name']);
$email = mysqli_real_escape_string($connection,$_POST['email']);
$bankid = mysqli_real_escape_string($connection,$_POST['bankid']);
$phone = mysqli_real_escape_string($connection,$_POST['phone']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$query = "SELECT email FROM users where email='".$email."'";
$result = mysqli_query($connection,$query);
$numResults = mysqli_num_rows($result);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // Validate email address
{
$message = "E - post Redan also!!";
}
elseif($numResults>=1)
{
$message = $email." E-post redan finns!!";
}
else
{
mysqli_query($connection,"insert into users(name,email,bankid,phone,password) values('".$name."','".$email."','".$bankid."','".$phone."','".md5($password)."')");
$message = "Registrera framgångsrikt!!";
}
}
If I understand you correctly, you want to be able to validate all the fields of your sign up form on submit, correct?
There are various examples online of using filter_var in PHP - a bit of Googling will get you the answers.
I would recommend using a validation library that's built to help you make sure your code is secure. An example of such library is: https://github.com/Wixel/GUMP
If you have a look at the source code for GUMP, there are more examples using filter_var:
https://github.com/Wixel/GUMP/blob/master/gump.class.php#L878
filter_var($value, FILTER_SANITIZE_NUMBER_INT)
filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS);
// etc

PHP XSS validation not working

I have written a simple contact form script and am trying to add XSS validation to it using the method described on W3School. Unfortunately it doesn't work as if I enter a "<" in one of the fields and then submit, it comes out as "<" when I receive it via email.
Can anyone suggest what I'm doing wrong?
Data collection section
$name = $co = $email = $tel = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$name = test_input($_REQUEST['name']);
$co = test_input($_REQUEST['company']);
$email = test_input($_REQUEST['email']);
$tel = test_input($_REQUEST['tel']);
$message = test_input($_REQUEST['message']);
}
Data testing function
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Many Thanks
Maybe your email client is configured to show the email as HTML. htmlspecialchars will convert < to <
Try to display your email as plain text.

Categories