PHP: Form validation

Hi
I have a couple of questions regarding form validation

First is there a way to validate a name field

$FormError=0;
$name = filter_input(INPUT_POST, 'name');

if(empty($name) || strlen($name >250)){
  echo "Name Error";
$FormError++;
}

Open in new window


Second this isn't working

// HTML

<input type="text" name="nickName" placeholder="bondj007">

// PHP
$NickName = filter_input(INPUT_POST, 'nickName', FILTER_VALIDATE_REGEXP,array("options" => array("regexp"=>'/*\d{3}$/')));
            if (empty($NickName )  ){ 
             // no NickName this OK as not mandatory but if submited must have 3 numbers at the end
              }
           elseif(strcmp($NickName, "bondj007")){
// this isn't working
              echo"Are you really James Bond?";
                $FormError++;

           } 
         else{
              echo"Nick name Valid";
         }

Open in new window

LVL 1
trevor1940Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
First is there a way to validate a name field

Validate how - you need to specify a rule. I am guessing that you want a M < length > N and maybe some sort of Regular Expression check on chars - but we would need to know what

Secondly - when you say not working
a) What did you expect
b) What did you observe

Easier to answer if you can give us some clues on the above.
0
Chris StanyonWebDevCommented:
Firstly, what do you mean by validate! You can validate any data in PHP as long as you know what you want to validate against.

Looking at your code you're trying to make sure the $_POST['name'] isn't empty and is less than 250 characters. You have a bracket in the wrong place in your strlen() function. It should be:

if( empty($name) || strlen($name) >250 ) {

As for your second part, there are a few issues. The regex for a string ending in 3 characters looks a little off. Try this:

"/^.+?\d{3}$/"

filter_input will return false if it fails the regex check, so if someone enter "Nick", the $nickName will be 'false'.

You're also using the strcmp() function. This is a binary comparison, and you should probably be using an equality operator (==).

A quick example of what you probably need:

if ( ! empty($_POST['nickName']) ):

    $pattern = "/^.+?\d{3}$/";
    $nickName = filter_input(INPUT_POST, 'nickName', FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => $pattern)));

    if ( ! $nickName): // we failed the regex validation
        echo "Nickname doesn't contain 3 numbers";
    else: // we passed the regex validation
        if ($nickName == "bondj007"):
            echo "Are you really James Bond?";
        else:
            echo "Nickname is valid";
        endif;
    endif;

endif;

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
trevor1940Author Commented:
Thanx Chris I'll test it tomorrow on the live  script I suspect some of your  points are due to typos

When I asked about validating a name I was hopping for how experts do it

$name ="Robert'); DROP TABLE Students;";

Open in new window


Probably isn't valid but bellow could be

$name="Chloé Double-Barrel O'Tool";

Open in new window



As for the 2nd part I was using === to compare the strings which seemed to fail  google suggested to use  strcmp()

The logic is if the user wishes to enter a Nick Name it has to end with 3 numbers but cannot be "bondj007"
0
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Chris StanyonWebDevCommented:
No worries.

Don't believe everything you read on Google ;)

strcmp() does a binary comparison, so it's used for checking higher / lower, as in alphabetical. It will return -1 if str1 is less than str2, 1 if str1 is greater than str1 and 0 if they're equal. You were checking for a boolean, so if the strings matched, it would return 0, which equates to boolean false, so it's not the correct function to use. Just do a simple equality (==).

Still not sure what you mean by validate. Based on your example, I'm guessing Chloé Double-Barrel O'Tool (great name!) would be valid, so you wouldn't want to filter anything out.

If you're planning on doing any DB work with it, then you should be using a prepared statement, so apostrophes won't be an issue, and you should configure your whole app (php / html / db) to use utf8 encoding so the accented letters won't be an issue either. IMO - those 2 points are how Experts would generally deal with it as a good starting point :)
0
trevor1940Author Commented:
IMO - those 2 points are how Experts would generally deal with it as a good starting point

Thanx for the tip I guess was expecting something complex but that adherers  to the KISS principle which works for me

I'm assuming I put "header('Content-Type: text/html; charset=utf-8'); in my  PHP files will sort the encoding?
0
Chris StanyonWebDevCommented:
Regarding the header - it depends. If your PHP is outputting data that will be used in the HTML file, then it's the HTML that needs the encoding:

<head>
    <meta charset="utf-8">
    ...

If you're connecting to a database then you need to setup the connection to use utf8. For PDO, set it in the DSN:

$dsn = 'mysql:host=localhost;dbname=yourDb;charset=utf8mb4';

And for mysqli, set it on the connection:

$db = new mysqli($hostname, $username, $password, $database);
$db->set_charset("utf8");

You'll need to make sure your tables are setup to use utf8, and that's done at the mysql server level.

That should give you a good starting point for a utf8 compatible app.
0
trevor1940Author Commented:
Thanx Chris for help and the additional tips on UTF8

I've come to the conclusion you can't validate a name because there isn't any rules that govern names other than length but even that is arbitrary so as long as the name is handled as free text correctly the application should be OK
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.