php - preg_match to sanitize input for the best security

I am working on a wordpress website (i am new to web development). I installed a theme and now I am looking to improve it and make it suit my needs. Regarding the register form, the theme's code to check for invalid characters in the password is this:
else if(preg_match("/^([a-zA-Z0-9@#-_$%^&+=!?]{1,20})$/", $data['user_password'])==0) {
SendtoUSER::$messages[]=__('Forbidden characters detected', 'mytheme');
and for the username is this
if(preg_match('/[@\s]/', $username)) {
$valid=false;
}
I did some research and i understand most of the expression"/^([a-zA-Z0-9@#-_$%^&+=!?]{1,20})$/"
- what i don't get is why ; is still valid to use (i observed that removing#-_
prevents;
from working, so is#-_
an inverval?) My question is what@#-_$%^&+=!?
means in the expression? Is this code good enough, what are some good practices to implement preg_match for max security? Thanks in advance for your reply.
Answer
Solution:
I guess in WordPress, thesanitize_text_field
will be the best solution to do it. You can validate it:
if ( sanitize_text_field( $data['user_password'] ) !== $data['user_password'] ) {
$valid=false;
}
Also, I've checked how it works on the Profile page, and it looks like in the core, it validates as:
$pass1 = trim( $_POST['pass1'] );
//...
// Check for "\" in password.
if ( false !== strpos( wp_unslash( $pass1 ), '\\' ) ) {
$errors->add( 'pass', __( '<strong>Error</strong>: Passwords may not contain the character "\\".' ), array( 'form-field' => 'pass1' ) );
}
Probably the best solution is copying the WordPress solution as well.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: cannot access offset of type string on string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.