0

I have been stuck on this for some time now. I have a form that is located in index.php. The data is sent to a php file called, processuserform.php. I extract all the inputs and assign them each to their own variable. Does the following look like it is the proper way to validate and sanitize a form on Server side?

First is the form itself then the PHP file will be used to process the data sent to it.

<form method="POST" name="signup" action="php/processuserform.php">

    <input id="firstname" onkeyup="validateFirstName()"  placeholder="First Name" type="text" /><label id="firstnameprompt"></label>

    <br><br>

    <input id="lastname" onkeyup="validateLastName()"  placeholder="Last Name" type="text"/>
    <label id="lastnameprompt"></label>

    <br><br>

    <input id="Email" onkeyup="validateEmail()"  placeholder="Email" type="text" />
    <label id="Emailprompt"></label>

    <br /><br />

    <input id="Password" onkeyup="validatePassword()"  placeholder="Create Password" type="password" /><label id="Passwordprompt"></label>

    <br /><br />

    <strong>Male</strong><input id="Gender" type="radio" name="sex" value="male">
    <strong>Female</strong><input id="Gender" type="radio" name="sex" value="female">

    <br /><br />

    Click "Submit" if you agree to <a href="#">"Terms And Conditions"</a>
    <br>
    <input id="submit" onclick="return validateUserRegistration()" value="Submit" type="submit" name="submit"/>
    <label id="submitprompt"></label>
    <br><br>

processuserform.php

<?php

$first_name = ($_POST['firstname']);
$last_name = ($_POST['lastname']);
$email = ($_POST['Email']);
$pw = ($_POST['Password']);
$gender = ($_POST['Gender']);

// define variables and set to empty values
$first_nameErr = $last_nameErr = $emailErr = $pwErr = $genderErr = "";
$first_name = $last_name = $email = $pw = $gender = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    if (empty($_POST["firstname"]))
    {
        $first_nameErr = "Name is required";
    }
    else
    {
        $first_name = test_input($_POST["firstname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$first_name))
        {
            $first_nameErr = "Only letters and white space allowed";
        }
    }

    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        if (empty($_POST["lastname"]))
        {
            $last_nameErr = "Name is required";
        }
        else
        {
            $last_name = test_input($_POST["lastname"]);
            // check if name only contains letters and whitespace
            if (!preg_match("/^[a-zA-Z ]*$/",$last_name))
            {
                $last_nameErr = "Only letters and white space allowed";
            }
        }

        if (empty($_POST["Email"]))
        {
            $emailErr = "Email is required";
        }
        else
        {
            $email = test_input($_POST["email"]);
            // check if e-mail address syntax is valid
            if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
            {
                $emailErr = "Invalid email format";
            }
        }

        if (empty($_POST["Password"]))
        {
            $pwErr = "Password is required";
        }
        else
        {
            $pw = test_input($_POST["Password"]);
        }
    }
    if (empty($_POST["Gender"]))
    {
        $genderErr = "Gender is required";
    }
    else
    {
        $gender = test_input($_POST["Gender"]);
    }
}

function test_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

$hostname="this is correct";
$username="this is correct";
$password="this is correct";
$dbname="this is correct";

$db_conx = mysqli_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");

if(mysqli_connect_errno())
{
    echo mysqli_connect_error();
    exit();
}

$select = mysqli_select_db($db_conx,$dbname);

mysqli_query($db_conx,"INSERT INTO users (firstname, lastname, email, password, gender)
    VALUES ('$first_name', '$last_name', '$email', '$pw', '$gender')");
mysqli_close($db_conx);

header("Location: not/important.php")
?>

Thanks all for your help. If I am sanitizing it and validating it wrong would someone mind giving me an example of how it should look using one of my inputs as an example? I could use help as this is a bit confusing. Thanks again!

1

3 Answers 3

2

You definitely want the validation server-side (doing validation in javascript does not protect your data at all!) In any case you should let the user enter form data, POST that, validate it and if there are errors get your php to re-write the form with existing data filled in (so the user doesn't have to enter it again) and messages against the entries with an error.

i.e. something like: (much simplified!)

echo '<input id="firstname" value="' . $first_name . '"/>';
if( $first_nameErr != "" )
   echo 'Error: '.$first_nameErr;

Yours, TonyWilk

Sign up to request clarification or add additional context in comments.

Comments

1

Javascript validation is good but only for UI purpose, because a user can bypass that validation as javascript is client based.

For javascript disabled, i will follow Kuroi Neko as he explained well.

Regarding to php side validation and javascript validation, you can keep both, it will be not a problem. But in today good practices, i think you should work with ajax based forms which is a good option and also you will have no need to repopulate your forms if an error occurred (I am considering that javascript is always enabled).

You will have to do all your validation at server side in php code which can't be bypassed by a user. After the form is submitted by ajax, you validate all the form fields there. If there is an error, then return errors messages to ajax request and display them. If there are no errors, then do what ever you want to do with the form data and then return a success message to ajax request.

Based on the returned message(s) to ajax request, you can do what ever you want, display errors / success messages, redirect user to another page after success, or just hide the form and display the success message.

For ajax form submission, i will suggest you use JQuery Form plugin . It is very easy to use and support different data types like json, xml and html. On the example page, then have listed working codes, so you can easily adopt it.

1 Comment

Thank you for your information. I will look into the ajax based forms. From what I hear it sounds like it is a much better experience for the user and the designer.
0

You did not show your JavaScript validation code.

Trouble is, you will perform the same checks first in JavaScript and then in PHP. If for some reason the validation functions don't match, the result might be inconsistent.

My advice is:

1) if you are not planning to support browsers with JavaScript disabled, simply drop the PHP validation

2) if you want to support no-script browsers, you should detect that JS is disabled and warn the user that the form might be rejected after validation (it can be really frustrating to fill-in a long form only to get an error after submitting it)

If you support both validations simultaneously, you should make your best efforts to have symetrical validation code, using the same regexps and doing the checks in the same order.

It is not easy to share code between JS and PHP, but you could design a common format to validate the fields and have a JS and PHP validation engine use the same field definitions.
That would be the most consistent approach, but it's a lot of work, so if you only have a single form to validate it might not be worth the effort.

EDIT: to answer your additional remarks and questions

For ease of use, it is much better to have JavaScript check form data on the fly. It allows the user to know all proper informations have been entered before submitting the form.
PHP validation would produce an error page and force the user to go back to the form page, and (depending on the browser) possibly retype the whole set of informations unless you added some PHP code to fill the fields with previous values.

You should resort to PHP validation only if JavaScript is disabled or if you want to prevent malicious submissions (i.e. some hacker simulating a post request without using your form).

About supporting no-script browsers, I would say 90% of modern sites won't work properly (or offer a poor user experience) with JavaScript and/or cookies disabled, so that would not be such a big deal IMHO.
It all depends what kind of audience you're targeting.

5 Comments

Thank you for your information. I am wanting to support those who have Javascript enabled and those who dont. I was not aware that the Javascript and the PHP should be the same. I will readjust my PHP to match my Javascript. Am I sanitizing and validating the data above by doing it how I did or no? I really appreciate your reply.
I have two forms in index.php. One for users and one for business's. I am just trying to get the users one completed and then I will work on the business's.
Would it be smart to not allow browsers who have javascript turned off?
No, that would not be smart (if security is your concern here) … the user can still manipulate data that is send with JS turned on – and the client that sends data to your server does not even have to be a “browser” …
@CBroe That's what I said. However, if the aim is to protect from malicious posts, the checking can be a lot more brutal (i.e. you don't have to play nice in case of invalid input).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.