php - How to safely sanitize / escape text in a wordpress widget input field (html capable)


I have a question for the PHP / wordpress pros, concerning safe programming techniques. (Edit - the short version:) If I want a user to be able to enter hmtl into a text field in a wordpress widget backend, is it safe enough to just do with using esc_attr in the input field code?

Currently I am using this code for the input fields:

  <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
  <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
  <label for="<?php echo $this->get_field_id( 'mycode_content' ); ?>"><?php _e( 'Inhalt:' ); ?></label>
  <textarea id="<?php echo $this->get_field_id( 'mycode_content' ); ?>" name="<?php echo $this->get_field_name( 'mycode_content' ); ?>" rows="5"><?php echo esc_attr( $mycode_content ); ?></textarea>

Then the values the user enters are applied:

public function update($new_instance, $old_instance)
    $instance = array();
    $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
    if(current_user_can('unfiltered_html')) {
        $instance['mycode_content'] = $new_instance['mycode_content'];
    } else {
        $instance['mycode_content'] = wp_kses_post($new_instance['mycode_content']);
    $instance['filter'] = 'mycode_content';
    return $instance;

There is no sanitation done when outputting all this to the frontend:

if(!empty($title)) {
    echo $args['before_title'] . $title . $args['after_title'];
if(!empty($mycode_content)) {
    echo $mycode_content;

So Im using esc_attr when displaying title and content in the backend and strip_tags for the new title after it is input. I basically copied this from the wordpress text widget. But is it safe? For example, there is this line in the input code block:

if ( current_user_can( 'unfiltered_html' ) )

If this tests to yes then we just copy the input from the user into the database without further sanitzing. This makes me kind of nervous, I would hate it to do something wrong here.

People are also looking for solutions to the problem: php - Custom 404 in Silex


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.

Ask a Question

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.

Similar questions

Find the answer in similar questions on our website.