0

I'm trying to create a simple validation script for a form but cannot get it to work properly. I only get redirected to an error page...

As you can see below only small and capitalized letters are allowed for first- and last name, only email structure for email and only numbers, spaces and (+) for the phone number. If the user input is not allowed the user gets redirected to a simple error page.

$first_name = $last_name = $email = $mobile = $country = "";

if (isset($_SERVER["REQUEST_METHOD"] == "POST")) {

    // Only small and capitalized letters allowed
    $first_name = test_input($_POST['first_name']);
    if(!preg_match("/^[a-zA-Z ]*$/",$first_name)) { 
        die("Error! Non allowed signs were used in 'first name'");
    }

    // Only small and capitalized letters allowed
    $last_name = test_input($_POST['last_name']);
    if(!preg_match("/^[a-zA-Z ]*$/",$last_name)) { 
        die("Error! Non allowed signs were used in 'last name'");
    }

    // Only email allowed
    $email = test_input($_POST['email']);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        die ("Error! Non allowed signs were used in 'email'");
    }

    // Only numbers, space and + allowed
    $mobile = test_input($_POST['mobile']);
    if(!preg_match("/^[0-9 +-]+$/",$mobile)) { 
        die ("Error! Non allowed signs were used in 'mobile'");
    }

    // Country input (no validation)
    $country = $_POST['country'];

    }

    // Function test input
    function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }

The HTML is basically this:

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 

    <input type="text" required="" name="first_name" style="width:100%" />

    [And so on...]

</form>
1
  • Can you show redirection code? Commented Dec 15, 2017 at 15:50

1 Answer 1

2
if (isset($_SERVER["REQUEST_METHOD"] == "POST")) {` 

is incorrect ~ isset returns a boolean which effectively makes this if(false=='POST') or similar

Try:

if ( $_SERVER["REQUEST_METHOD"] == "POST" ) {
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.