What is the alternative code to if (isset ($_POST) && !empty ($_POST) to avoid warnings?

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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).

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x