I’m capturing username, email and password in a custom registration form on my WordPress site. I’m sanitising the username using sanitize_user()
and sanitize_email()
sanitises the email address.
For example:
$username = sanitize_user( $username );
$email = sanitize_email( $email );
How should I sanitise the password entered by the user? All I can think of is sanitize_text_field( $pass )
but I’m sure that isn’t the right way to do it.
Ref:
Sanitizing won’t necessarily protect you from injection. To protect against that you need to use prepared statements – or in the case of WordPress, use the $wpdb class.
Sanitization simply strips invalid characters, in the cases you’ve given above, it removes characters not allowed in usernames, or are not allowed in a valid email address. Passwords allow lots of different character types because that’s what makes them ‘strong’ so you don’t want to strip them out.
If you’re using
wp_insert_user()
to create a WP User, then you don’t need to sanitize any of it anyway, the function will take care of it all for you.wp_insert_user()
state of sanitization and filters as off (2021) WordPress5.7
wp_insert_user()
anduser_pass
by default:user_pass
viawp_hash_password()
.wp_insert_user()
anduser_login
by default:user_login
viasanitize_user()
.user_login
viaempty()
.user_login
viamb_strlen
. (60 characters maximum).user_login
viausername_exists()
to users.user_login
viaillegal_user_logins
to illegal user logins.wp_insert_user()
anduser_nicename
by default:user_nicename
viasanitize_user()
.user_nicename
viamb_strlen
. (50 characters maximum).user_nicename
viasanitize_title()
.wp_insert_user()
anduser_email
by default:user_email
viaempty()
.user_email
viastrcasecmp
to old.user_email
viaemail_exists()
to old.wp_insert_user()
anduser_url
,display_name
,nickname
,first_name
,last_name
,last_name
,description
, by default:Sources
user.php
@ https://github.com/WordPress/WordPress/blob/master/wp-includes/user.phpAs mentioned you can use the
sanitize_text_field()
function. It may cause some issues on some crazy passwords with special characters etc.But it should be okay.