WordPress Plugin Security: Data Validation
Data validation in WordPress plugin concern with the pattern of data processed by the plugin. Data with certain context should match the pattern generally acceptable. For example:
- Phone number only contain numerical content
- Postal code data contain valid postal code for designated country
- Required fields must be filled before processing
The process of validation should be done as early as possible to save resource and mitigate errors. This can be done throug JavaScript on the front end or PHP code in the plugin.
Lets try an example on Phone number
<?php
function is\_phone\_number($phone\_number){
if ( empty( $phone\_number ) ){
return false;
}
if ( strlen( trim($phone\_number) ) > 17 ){
return false;
}
if ( ! is\_numeric( $phone\_number ) ){
return false;
}
return true;
}
The function above can be used to validate phone number. There are some optimization which can be added for example using regex instead of is_numeric to check exact numbers for countries. But for general phone numbers this function should do well to validate them
This function utilized as if condition can serve as a gatekeeper when we work with phone number to ensure befor we do any actions the number is valid one. An example for the function usage is if there is a field of phone_number which we try to process
if ( isset( $\_POST\['phone\_number'\] ) && is\_phone\_number($\_POST\['phone\_number'\] ){
// do something
}
Various PHP functions and WordPress core functions can serve as validation tools. Some examples can be seen in the reference bellow.
References: