Frage

I am trying to insert some php code to my WordPress website but it gives security warnings perhaps due to directly accessing $_POST variable.

Instead of $name = $_POST['name'];, I can use $name = filter_input(INPUT_POST, 'name'); however I am not able to figure out what alternative piece of code I should use instead of if(isset($_POST) && !empty($_POST)) { //some code }?

Thanks for your help in advance.

War es hilfreich?

Lösung

filter_input is the proper way to go. If it doesn't return anything valid, it will return null:


$myvar = filter_input( INPUT_POST, 'something', FILTER_SANITIZE_STRING );

if ( empty( $myvar ) ) {
    // Do whatever you would have done for ! isset( $_POST['something'] )
}

// Use $myvar

filter_input won't throw any notices if the requested index isn't found, so it's like having isset built-in to the function.

Edit: just be sure to use a FILTER_ to sanitize or validate, and note there are some gotchas that are documented in PHP's documentation about these. For most general use-cases they should work fine, but always validate your user input appropriately once you have it (the same as you would when getting it directly from $_POST).

Andere Tipps

Though the error was not caused by accessing $_POST variable directly, but I was able to write the alternative to if(isset($_POST)).

Firstly, you need to give a name to the submit button in your form. Your form should look like,

<form action = "" method = "post">
   Some fields.
   <input type = "submit" name = "submit_button" />
</form>

And then on the php side,

$submit =  filter_input(INPUT_POST, 'submit_button');
if (isset($submit)){
       //some code.
}

Hope this helps someone.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit wordpress.stackexchange
scroll top