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.
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.
Share Improve this question asked Dec 18, 2020 at 15:20 Asmat AliAsmat Ali 1392 silver badges10 bronze badges 1- 1 What security warnings and where? Please add that detail to your question. If you are linting your PHP with a tool like PHPCS you will likely see a "super global" warning, for example. – jdm2112 Commented Dec 18, 2020 at 16:05
2 Answers
Reset to default 1filter_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
).
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.