最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

post meta - Sanitizing integer input for update_post_meta

programmeradmin2浏览0评论

When updating a post meta where the input will be always an integer, should I use (int) or is there a WordPress function for that (eg. sanitize_text_field)?

For example:

if(isset($_POST['category_id'])){
    update_post_meta($post->ID, 'category_id', (int)($_POST['category_id']));
}

When updating a post meta where the input will be always an integer, should I use (int) or is there a WordPress function for that (eg. sanitize_text_field)?

For example:

if(isset($_POST['category_id'])){
    update_post_meta($post->ID, 'category_id', (int)($_POST['category_id']));
}
Share Improve this question edited Jan 28, 2020 at 16:42 butlerblog 5,1213 gold badges28 silver badges44 bronze badges asked Nov 13, 2014 at 7:04 asamasam 811 gold badge1 silver badge2 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 7

For integers KSES has no special function.

Use (int) or intval() or absint()

See more: Data Validation - Integers

&safe_id = intval( $_POST['category_id'] );
if ( ! $safe_id ) {
  $safe_id = '';
}

update_post_meta( $post->ID, 'category_id', $safe_id );

The intval() function casts user input as an integer, and defaults to zero if the input was a non-numeric value. We then check to see if the value ended up as zero. If it did, we'll save an empty value to the database. Otherwise, we'll save the properly validated category_id.

Use a conditional statement to check if $_POST['category_id']) is an integer first. The PHP function is is_int()1

if(isset($_POST['category_id']) && is_int($_POST['category_id'])){
    update_post_meta($post->ID, 'category_id', $_POST['category_id']);
}

You should also trim whitespace on your $_POST data because is_int() will return false if the string has whitespace2.

发布评论

评论列表(0)

  1. 暂无评论