简体   繁体   中英

Is there any short hands for user input validation in php?

for example, I have a register function, that need the user input their "user name", "email address", and "password".

I need to check all the parameter from the user, which is not null, furthermore, I need check their input length that is short enough to store in the db. Moreover, I need check is there any duplicated user name and email in the db. Also, I need to check the email address is a valid email format.

Only create a simple enough register function, I need do so many checking. Is there any short hands for checking some basic stuff? for example, which is not null to increase the productivity.

You need to check it all because it can't check itself.

PHP has a number of useful functions to assist...

isset()

isset() to ensure the GET / POST variables are set. These missing are generally only caused by people tinkering.

Example

if ( ! isset($_POST['email'])) {
   $this->addError('You did not supply your email');
}

trim() and empty()

trim() and empty() for making sure someone entered some text other than whitespace. Note that empty() is a construct and must be called on a variable, not the string returned by trim() directly (my guess because it wants to examine a block in memory, not a value on the stack).

Example

$email = trim($_POST['email']);

if (empty($email)) {
   $this->addError('You didn\'t type any non whitespace characters');
}

Of course, use a better error that your end users will understand.

This is also used so often you could make a utility function that does this.

filter_var()

You can use filter_var() for validating things, such as validating emails, IPs and integers.

Example

if ( ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
   $this->addError('You did not enter a valid email');
}

Regular Expressions

Regular Expressions can do a lot by themselves, such as checking for valid characters, patterns and lengths.

Example

if ( ! preg_match('/^\w{4,12}\z/', $username)) {
   $this->addError('You did not enter a valid email');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM