4

I am working on a WordPress plugin and need to sanitize the POST data within this function. Would sanitize_text_field() be the best way to go about it? Also what is the proper way to add it to the code below?

header( 'Content-Type: application/json' );

        global $wpdb;
$session_id = $_POST['session_id'];
        $procedure_name =  $wpdb->prefix . 'get_geojson_route';
        $gps_locations = $wpdb->get_results($wpdb->prepare(
            "CALL {$procedure_name}(%s);", 
            array(
                $session_id
            )
        )); 
stpetedesign
  • 75
  • 1
  • 8
  • 1
    Sadly, the best way would be not to use Wordpress whatsoever. The other good way would be to start by defining what *sanitize* means to you. This snippet you posted is everything that's bad with Wordpress and practices it encourages.. you're accepting a function name from user input. That lets me stick any kind of crap in. It doesn't even matter if I break something, I can make your site error out and obtain info I'm not supposed to see. And there's the question of whether calling the procedure is the right tool for the job.. – N.B. Apr 05 '18 at 20:46

4 Answers4

8

To sanatize post data wordpress give function :

$title = sanitize_text_field( $_POST['title'] );

Try this

Rakhi Prajapati
  • 880
  • 1
  • 12
  • 24
2

In PHP you can do as:

// it prevents from XSS
$_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

This will sanitize your $_GET and $_POST arrays.

More details: PHP -Sanitize values of an array

If you want it in WordPress see this link:

https://code.tutsplus.com/articles/data-sanitization-and-validation-with-wordpress--wp-25536

Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
  • This worked well for some of my needs, but when processing the contents of an ACF WYSIWYG editor, it stripped out a lot of the HTML markup. I didn't spend the time to figure out why—this is just a note in case anyone else runs up against this behavior. – Sarah Lewis Oct 29 '22 at 19:24
1

Using $wpdb->prepare is doing the sanitizing for you

1

If your PHP version is older than 8.1 then you can use

$form_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );

Else you can use

$form_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS );
Reza Khan
  • 86
  • 3